javascriptregexvuejs2rulesvuetify2

Passing dynamic values inside a regular expression statement is not working?


I have a validation rule on an input field that allows a maximum of three words to be typed and I am using a regex rule (/^\s*(?:\S+(?:\s+\S+){0,2}\s*)?$/) to validate this.

Now, I don't want to hardcode this maximum limit of 3 and use it like this {0, 2}. So, I am passing the limit dynamically and using it inside the regex but the regex is not working properly and I also don't know if it's the right syntax or not.

I tried the following syntaxes but nothing worked-

1. `${/^\s*(?:\S+(?:\s+\S+){0,${max-1}}\s*)?$/}`

2. /`${^\s*(?:\S+(?:\s+\S+){0,${max-1}}\s*)?$}`/

3. new RegExp(`${/^\s*(?:\S+(?:\s+\S+){0,${max-1}}\s*)?$/}`)

I tried looking at similar questions as well but didn't found much luck.

Here is an example with the hardcoded regex expression, and dynamic regex expression.

Steps to test the issue-

  1. Try to type more than 3 words in the first input, it should throw an error, "Max 3 words are allowed". (Working fine)
  2. Try to type anything in the second input, it will throw an error from the start. (Not working)

<!DOCTYPE html>
<html>
  <head>
    <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
  </head>
  <body>
    <div id="app">
      <v-app>
        <h3>
        Hardcoded Max Limit (Working)</h1>
        <v-text-field
          v-model="queryH"
          :rules="[rules.maxWordsH()]"
          dense
          ></v-text-field>
        <h3 class="red--text">
        Dynamic Max Limit (Not Working)</h1>
        <v-text-field
          v-model="queryD"
          :rules="[rules.maxWordsD(3)]"
          dense
          ></v-text-field>
      </v-app>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
    <script>
      new Vue({
        el: '#app',
        vuetify: new Vuetify(),
        data() {
          return {
            queryH: null,
            queryD: null,
            rules: {
              maxWordsH() {
                return (v) =>
                  (v || "").match(/^\s*(?:\S+(?:\s+\S+){0,2}\s*)?$/) ?
                  true :
                  "Max " + 3 + " words are allowed";
              },
              maxWordsD(max) {
                return (v) =>
                  (v || "").match(`${/^\s*(?:\S+(?:\s+\S+){0,${max-1}}\s*)?$/}`) ?
                  true :
                  "Max " + max + " words are allowed";
              },
            },
          };
        },
      })
    </script>
  </body>
</html>


Solution

  • ** You can try this, When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. **

     new RegExp(`^\\s*(?:\\S+(?:\\s+\\S+){0,${max-1}}\\s*)?$`)