Validates_format_of with condition

Hi,
I am trying to validate the email format by using “validates_format_of”.
I have written a code like this:-
"validates_format_of :email,
:with=>/^[0-9a-zA-Z_][\w.-][a-zA-Z0-9_]@[a-zA-Z0-9][\w.-][a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$/,
:message => “is not valid” "

It is working fine, but in my application email id is not manadatory.
So how should add the condition in this validator so that it will
validate the email only when the email address is present.

Can anyone help me out?

Thanks,
Tushar

Tushar G. wrote:

Hi,
I am trying to validate the email format by using “validates_format_of”.
I have written a code like this:-
"validates_format_of :email,
:with=>/^[0-9a-zA-Z_][\w.-][a-zA-Z0-9_]@[a-zA-Z0-9][\w.-][a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$/,
:message => “is not valid” "

It is working fine, but in my application email id is not manadatory.
So how should add the condition in this validator so that it will
validate the email only when the email address is present.

Can anyone help me out?

Thanks,
Tushar

Have you considered :unless

Hi,
Use allow_blank => true

:allow_nil => true

validates_format_of :email,
:with=>/^[0-9a-zA-Z_][\w.-][a-zA-Z0-9_]@[a-zA-Z0-9][\w.-][a-zA-
Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$/,
:message => “is not valid”,
:unless => Proc.new { |your_model_name_or_any_variable_name_you_want|
your_model_name_or_any_variable_name_you_want.email.blank?}

So, supposing your model is a User:

validates_format_of :email,
:with=>/^[0-9a-zA-Z_][\w.-][a-zA-Z0-9_]@[a-zA-Z0-9][\w.-][a-zA-
Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$/,
:message => “is not valid”,
:unless => Proc.new {|user| user.email.blank?}

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs