0

I have a regular expression I've adapted from Michael Hartl's rails book that I'm using to validate email addresses

/\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i

I want to use this for validation in javascript, but it doesn't work there, and I can't seem to figure out why. I'm just spinning my wheels here

So the above one works in Rails, but doesn't work in JS. I've found other expressions I can use in JS that work, but I want to try to use the same ones to keep it consistent.

For clarification, this is the rails side:

email = "test@test.com"

return /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i

this returns true

and on the JS side:

email = "test@test.com"

return /^\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i.test( email );

this returns false

Any pointers?

Spance
  • 555
  • 3
  • 11
  • 29
  • 2
    In JS, use `^` instead of `\A` and `$` instead of `\z`. `\A` is treated as `A` and `\z` as `z` since these are unknown regex escapes. Or do you want to say you cannot use two different patterns? – Wiktor Stribiżew Apr 28 '17 at 16:13

1 Answers1

0

Per the comment by @Wiktor Stribiżew the missing piece was changing the regex syntax to work with JS, like this

return /^([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+$/i.test( email );

I took out the \A and \z and replaced them with \^ and $, respectively

Spance
  • 555
  • 3
  • 11
  • 29