0

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

anujjain0801
  • 122
  • 3

3 Answers3

0

Validating regex patterns ,It will be like counting infinity because You have two things with regex

  1. Validating the syntax

  2. 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

Community
  • 1
  • 1
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
0

you can use eval(), but its taxing

var regex_from_input = '/^asd$/';
        try{
            eval(regex_from_input);
        }catch(e) {
            //do stuff
        }
Kaushal Niraula
  • 563
  • 3
  • 7
0

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);" />
Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36