reactjsregexvalidationemaileslint

ReactJS - How to fix regex error for email validation?


In react app, I am using regex to check email format. Actually its working fine but there is a CodeQL error like This part of the regular expression may cause exponential backtracking on strings containing many repetitions of '+'.

In /index.js,

const emailRegex = RegExp(/^[\w-_+]+([.-]?[\w-_+]+)*@[\w-_+]+([.-]?[\w-_+]+)*(\.[\w-_+]{2,})+$/)
if (!emailRegex.test(email)) {
  setError("Invalid email")
}

If I try to add \ to fix then will get an eslint warnings. Please suggest me the answer which works in both cases.


Solution

  • I did that:

     var emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (!emailRegex .test(email)) {
            setError("Invalid email")
            }