I have a requirement wherein my form I have a textbox and user can enter any regex expression. Is there a way I can validate the regex expression given by user as input in form textbox using JavaScript/Jquery
-
please provide more information – Ganesh Sagare Aug 17 '16 at 17:22
-
By validate do you mean: check to see if the regex they submitted was valid regex? Or do you mean: check to see if the regex they submitted would match the expected results? – Pat Aug 17 '16 at 17:23
-
Yes i want to check to see if the regex they submitted was a valid regex.. – anujjain0801 Aug 17 '16 at 17:25
-
Call the RegExp constructor with the pattern within a try block – Lucas Trzesniewski Aug 17 '16 at 17:38
3 Answers
Validating regex patterns ,It will be like counting infinity because You have two things with regex
Validating the syntax
Validate it huge possibilities of test cases
Regex is not a language hence cannot be parsed by any regex so what you can do is limit your boundaries by putting constants on area covered by used regex so like you can say enter regex for email and then you can validate it against your pattern and then against couple of hard examples.
There are couple of patterns which can be used link but again regex has no particular boundary ,read the discussion in the link which will state this fact and there is also something known as recursive regex which is not supported by all platforms

- 1
- 1

- 36,884
- 5
- 53
- 68
you can use eval()
, but its taxing
var regex_from_input = '/^asd$/';
try{
eval(regex_from_input);
}catch(e) {
//do stuff
}

- 563
- 3
- 7
You can try - catch
user input using new RegExp
constructor. Something like this.
function validateRegExp(str){
try{
var re = new RegExp(str);
console.log(re);
return true;
}
catch(e){
console.log(e.message);
return false;
}
}
<input type="text" onchange="validateRegExp(this.value);" />

- 9,120
- 3
- 27
- 36