Solution 1 :

To validate if the user-inputted string is valid regex you can just do the following

try {
  // Handle correct regex-string here
} catch {
  // Handle invalid regex-string */

The code should be placed in either an onKeyUp or onChange reacting to the <input> with id regexInput.

Problem :

I’m not sure how else to phrase this other than I’ve got a form where a user can enter a regex, I’ve got form validation enabled but I’m struggling to validate this field to make sure it contains a valid regular expression.

I’m working in React with Redux and my whole form is in a form-component I’ve created, here is the small snippet of JSX with the field in question:

<div className="form-group">
    <label htmlFor="regexInput">Regex</label>
    <input required name="regexInput" onChange={e => setRegexInput(} type="text" className="form-control" id="regexInput"/>
    <div className="invalid-feedback">
        This field is required.

How do I make sure a user has entered a valid Regex? I tried using the regex mentioned here but I don’t think the JavaScript Regex Engine supports recursive regular expressions. Is anybody able to help?

Edit: I forgot to mention I’m using bootstrap for my validation – I’m not sure if that changes anything.


Comment posted by ChrisR

What is this regex used for? You could use the provided regex to test an element you know is true. Or if your regex must have only one shape, simply compare it to the correct one.

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

Does this answer your question?