问题
i need to validate differents input value lengths.
Inputs value can have a max length of 6 / 15 / 25 characters. Now i was asking to my self if it's a good practice use only one dynamic regex to validate differents max lengths, instead of copy paste the same regex.
During my research i found that i've to use the the const regex = new RegExp()
the problem is that i tried
const lengthValidation = () => {
const maxLength = 4;
const inputValue = 'ciao';
const regex = new RegExp(`/^.{6,${maxLength}}$/`);
const isValid = regex.test(inputValue);
return console.log('regexTest', isValid);
};
lengthValidation();
but it's invalid.
where is my mistake ?
回答1:
As said in the comments, you could simply use the +
operator as in
const lengthValidation = () => {
const maxLength = 4;
const inputValue = 'ciao';
let expression = '^.{' + maxLength + ',6}$';
const regex = new RegExp(expression);
const isValid = regex.test(inputValue);
return console.log('regexTest', isValid);
};
lengthValidation();
Be aware though that e.g. .{6,4}
will lead to an error as the engine requires the quantifiers to be in the correct order. You might build in a check before otherwise the expression will fail.
Additionally, for a simple length check, a regular expression might be a bit of an overkill.
回答2:
You should remove the slashes from the regex string. Slashes are only needed to create a Regex when you are using the var regex = /expr/;
notation.
Also, you need to use a lower bound of e.g. 1 character, not 6:
const lengthValidation = () => {
const maxLength = 4;
const inputValue = 'ciao';
const regex = new RegExp(`^.{1,${maxLength}}$`);
const isValid = regex.test(inputValue);
console.log(regex);
console.log('regexTest', isValid);
};
lengthValidation();
来源:https://stackoverflow.com/questions/59875470/dynamic-value-for-max-length-in-a-regex