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-
<!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>
** 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*)?$`)