2

I've got such a regex in ruby on rails

/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

I'd like to use same email validation logic in front end.

I've tried to use the .inspect method in the irb console, it doesn't seem to return a js valid regular expression.

As far as I understand \A is a ^, \Z is a $. [-a-z0-9] probably translates to [a-zA-Z0-9]. Not sure about the rest.

I've tried to look for an online converter too, couldn't find one. Answers in other similar topics in SO didn't work.

What's the easiest way to translate such regex from ruby into javascript?

2
  • Did you try to use it as is in javascript? What's the result>? Commented Jun 22, 2014 at 11:48
  • 1
    It should translate about 1 to 1, seems like you already pointed out some conversions except that [-a-z0-9] should remain unchanged. It matches any lower-case letter, a digit, or the dash (-). The dash has no special meaning at the start of a character class. Commented Jun 22, 2014 at 19:03

2 Answers 2

1

As stated by Daniel in the comment it should just translate one to one, I incorrectly assumed that [-a-z0-9] should be replaced.

Ruby version:

/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

JavaScript version:

/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/

Some tests:

/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test("[email protected]"); // true
/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test("test@emailcom");  // false
/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test("testemail.com");  // false
Sign up to request clarification or add additional context in comments.

Comments

0

Did you try this?

class Regexp
  def to_javascript
    Regexp.new(inspect.sub('\\A','^').sub('\\Z','$').sub('\\z','$').sub(/^\//,'').sub(/\/[a-z]*$/,'').gsub(/\(\?#.+\)/, '').gsub(/\(\?-\w+:/,'('), self.options).inspect
  end
end

When you render it to the client simply instantiate a new RegExp object with the resulting string:

new RegExp(regexpStringFromRuby);

Check the client_side_validations gem. It might be what you need.

1 Comment

I don't understand, should I create a Regexp class with the method defined above? Another thing I don't get, why the differet class names Rexexp vs. RegExp?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.