-2

I have the following regex pattern on an HTML input field, which is supposed to hold an email address:

<input type="text" pattern="^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,4})+$" /><br>

I furthermore have the same regex on an Express (JavaScript) backend using the following:

 var re-email = new RegExp("^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,4})+$")
   if (!re-email.test(email)) {
     validation = false
   }

Although the regex are exactly the same, a specific test input is evaluated as true on the front-end while as false on the backend.

Why is this?

Solution (found after the initial post):

Instead of using "new RegExp" (which is not working) as above, include the Regex within forward slashes as below (which works).

var re-email = /^\w+([.-]?\w+)@\w+([.-]?\w+)(.\w{2,4})+$/

JF0001
  • 819
  • 7
  • 30

1 Answers1

2

Probably not the answer you are after (not vue.js specific)...

Email address input validation should usually be completed like so:

<input type="email" name="" value="" required />

Specifying the correct "type" to an input field also adjusts input keyboards on mobile devices to make inputting an email address easier.


Your regular expression is poorly written and leads to "catastrophic backtracking" as well as not actually supporting valid email addresses.

Email address validation is generally complex, see this answer and associated question: https://stackoverflow.com/a/201378/406712


You can also find the HTML email address validation equivalent regular expression in the HTML spec: https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address


Also note you failed to escape the characters in the string, the first instance being the \w which without escaping the \ will appear as simply w.

Escaped the string it more like this:

'/^\\w+([.-]?\\w+)@\\w+([.-]?\\w+)(.\\w{2,4})+$/'
Dean Taylor
  • 40,514
  • 3
  • 31
  • 50
  • Thank you @Dean Taylor I have actually found a solution, which I have explained in the initial post above. I will nonetheless do more reading regarding the Regex itself, as you have suggested. – JF0001 Nov 19 '21 at 03:12
  • 1
    @JF0001 I've edited my answer to include a note about escaping characters which is that issue. – Dean Taylor Nov 19 '21 at 03:21
  • Great! Thank you @Dean Taylor – JF0001 Nov 19 '21 at 03:22