0

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(e.target.value)} type="text" className="form-control" id="regexInput"/>
    <div className="invalid-feedback">
        This field is required.
    </div>
</div>

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.

Jamie
  • 1,530
  • 1
  • 19
  • 35
  • 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. – ChrisR Jan 08 '20 at 12:28
  • Does this answer your question? [How to check if the input string is a valid Regular expression?](https://stackoverflow.com/questions/17250815/how-to-check-if-the-input-string-is-a-valid-regular-expression) – Yevhen Horbunkov Jan 08 '20 at 12:37

1 Answers1

0

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

try {
  RegExp(e.target.value);
  // 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.