Tintin81 Tintin81 - 9 months ago 31
Ruby Question

How to use regular expression from Rails backend in the frontend?

In my Ruby on Rails 4.2 application I am trying to use a regular expression from the backend in the frontend so I can run HTML5 validations on it:

# constants.rb
EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

# edit.html.erb
<%= f.email_field :email, :required => true, :pattern => EMAIL_REGEX %>

Unfortunately, in the HTML source I see the
attribute as


which is not what I want.

Can anybody help?


Note that \A, \z and the inline modifiers won't work in HTML5 pattern attribute. You need to use JavaScript pattern like

EMAIL_REGEX = "[\\w+.-]+@[A-Za-z\\d.-]+\\.[A-Za-z]+"

or (though the ^ and $ are redundant in HTML5 patterns as they are anchored by default):

EMAIL_REGEX = "^[\\w+.-]+@[A-Za-z\\d.-]+\\.[A-Za-z]+$"

Note that the pattern is passed as a string so that no inline modifiers could be added and the backslashes are doubled to introduce literal backslashes escaping regex metacharacters.

As for the backend, you may use your own regex that is tailored for RoR.