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:
EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
<%= f.email_field :email, :required => true, :pattern => EMAIL_REGEX %>
\z and the inline modifiers won't work in HTML5
EMAIL_REGEX = "[\\w+.-]+@[A-Za-z\\d.-]+\\.[A-Za-z]+"
or (though the
$ 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.