1

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 ?

Ele
  • 33,468
  • 7
  • 37
  • 75
Legeo
  • 784
  • 4
  • 20
  • 44
  • 1
    The expression is interpreted as a string, so you could simply concatenate it before using the `+` operator. – Jan Jan 23 '20 at 09:44
  • it was the template literals, thanks. Could you answer please :) you fixed it. – Legeo Jan 23 '20 at 09:47
  • 1
    The right value should be greater than the left value `{6,4} -> Wrong` – Ele Jan 23 '20 at 09:47

2 Answers2

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.

Jan
  • 42,290
  • 8
  • 54
  • 79
  • your previous example ```export const lengthValidation = (inputValue: string, minLength: number, maxLength: number) => { const regex = new RegExp(`^.{${minLength},${maxLength}}$`); const isValid = regex.test(inputValue); return console.log('regexTest', isValid); }; ``` was perfect to fix my case. I used ' ciao ' just a placeholder. – Legeo Jan 23 '20 at 09:54
0

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();
Peter B
  • 22,460
  • 5
  • 32
  • 69