-2

Need to validate an input using Regular expression

  1. It should accept only digit
  2. Min and max should be dynamic

Thanks for your help in advance

My code is

min=3, max=10

MyRegex is

/^(\d{min, max})$/
Syed mohamed aladeen
  • 5,943
  • 3
  • 25
  • 53

2 Answers2

0

I'd use a template string:

let min = 2;
let max = 4;

let r = new RegExp(`^\\d{${min},${max}}$`);

[
 '2',
 '1',
 '10',
 'aos',
 '3333',
 '33',
].forEach(s => console.log("%s\t: %s", s, r.test(s)));
Rafael
  • 6,646
  • 13
  • 29
  • 43
0

You can use template strings and RegExp constructor.

const test = (str,min,max) => new RegExp(`^\\d{${min},${max}}$`).test(str)
console.log(test('1234',2,4))
Maheer Ali
  • 32,967
  • 5
  • 31
  • 51