How to check if the input string is a valid Regular expression?

Here is a little function that checks the validity of both types of regexes, strings or patterns:

function validateRegex(pattern) {
    var parts = pattern.split('/'),
        regex = pattern,
        options = "";
    if (parts.length > 1) {
        regex = parts[1];
        options = parts[2];
    }
    try {
        new RegExp(regex, options);
        return true;
    }
    catch(e) {
        return false;
    }
}

The user will be able to test both test and /test/g for example. Here is a working fiddle.


You can use try/catch and the RegExp constructor:

var isValid = true;
try {
    new RegExp("the_regex_to_test_goes_here");
} catch(e) {
    isValid = false;
}

if(!isValid) alert("Invalid regular expression");

None of the answers here satisfied my need for checking that a string is a valid regex for other languages (Mostly php), because they either ignore the flags, the delimiters or escaped special characters, so I made my own function

function isValidRegex(s) {
  try {
    const m = s.match(/^([/~@;%#'])(.*?)\1([gimsuy]*)$/);
    return m ? !!new RegExp(m[2],m[3])
        : false;
  } catch (e) {
    return false
  }
}

console.log(isValidRegex('abc')) //False
console.log(isValidRegex('/abc/')) //True
console.log(isValidRegex('/ab#\/[c]/ig')) //True
console.log(isValidRegex('@ab#\/[c]@ig')) //Special delimiters: True
console.log(isValidRegex('/ab\/[c/ig')) //False
console.log(isValidRegex('/abc/gig')) //False

You can also derive this function to transform a string into a RegExp object

function stringToRegex(s) {
   const m = s.match(/^([/~@;%#'])(.*?)\1([gimsuy]*)$/);
   return m ? new RegExp(m[2], m[3]) : new RegExp(s);
}

console.log(stringToRegex('abc'))
console.log(stringToRegex('/abc/'))
console.log(stringToRegex('/ab#\/[c]/ig'))
console.log(stringToRegex('@ab#\/[c]@ig'))
try {
  console.log(stringToRegex('/ab#\/[c/ig'))
} catch (e) {
  console.log('Not a valid regex')
}

The question is solved, but if someone needs to define is the string either valid RegExp or not a RegExp at all.

You can use new Function() and templating inside of the function body with try ... catch and new RegExp() as mentioned earlier.

There is a snippet with the explanations:

const isRegExp = (string) => {
    try {
        return new Function(`
            "use strict";
            try {
                new RegExp(${string});
                return true;
            } catch (e) {
                return false;
            }
        `)();
    } catch(e) {
        return false;
    }
};

// Here the argument 'simplyString' shall be undefined inside of the function
// Function(...) catches the error and returns false
console.log('Is RegExp valid:', isRegExp('simplyString'));

// Here the argument shall cause a syntax error
// isRegExp function catches the error and returns false
console.log('Is RegExp valid:', isRegExp('string which is not a valid regexp'));

// Here the argument is not a valid RegExp, new RegExp(...) throws an error
// Function(...) catches the error and returns false
console.log('Is RegExp valid:', isRegExp('abc ([a-z]+) ([a-z]+))'));

// Valid RegExp, passed as a string
console.log('Is RegExp valid:', isRegExp('/^[^<>()[\]\\.,;:\s@\"]$/'));

// Valid RegExp, passed as a RegExp object
console.log('Is RegExp valid:', isRegExp(/^[^<>()[\]\\.,;:\s@\"]$/));

// Howewer, the code injection is possible here
console.log('Is RegExp valid:', isRegExp(');console.log("This is running inside of the Function(...) as well"'));