I am trying to validate fields in a form where I want two different messages for two different problems with the input.
I have the following code:
validates_format_of :email,
:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
:allow_blank => false
If the email field is left blank then the error message "Email is invalid" is shown in the website.
How can I get the validation to return a message saying the field cannot be blank if it is left out by the user, instead of just saying it is too short?
I like to handle this with 2 different validations (and make sure they don't both fire at the same time). So something like this:
validates_format_of :email,
:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
:allow_blank => true
validates_presence_of :email
The validates_presence_of
handles making sure the email is not blank. And changing validates_format_of
to use :allow_blank => true
will make sure the formatting validation won't run if the email is blank.
In Rails 3.0+ you can also combine the two validations into a single one using validates
:
validates :email,
presence: true,
format: { with: /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
allow_blank: true }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments