How to validate a form field sequentially


#1

First, sorry for my English :S …

Hi! I’ve searched about my problem into the forum but I didn’t find any
post.
When I fill, for example, an email field my model validates the
presence, uniqueness, max-length (128) and format (a regular
expression).
If a user doesn’t fill that field, the validation returns two messages:

  • The message about the field is blank (yeeeee).
  • The message about the field haven’t the correct format (buuuu).
    I only want to show the first message. Is there any way to do the
    validation sequentially and stop when a validation doesn’t be correct?
    an example: first => presence, second => format, third => max-length,
    fourth => uniqueness…

Last, sorry for my English :S …
Thanks!

Luis


#2

I’ve tought a solution, when it validates, it only takes the first error
message:

if obj.errors.on(:email)
errMsg << obj.errors.on(:email)[0]
end

Anybody knows a more elegant solution?
greetings!
Luis.

Luis Sánchez wrote:

First, sorry for my English :S …

Hi! I’ve searched about my problem into the forum but I didn’t find any
post.
When I fill, for example, an email field my model validates the
presence, uniqueness, max-length (128) and format (a regular
expression).
If a user doesn’t fill that field, the validation returns two messages:

  • The message about the field is blank (yeeeee).
  • The message about the field haven’t the correct format (buuuu).
    I only want to show the first message. Is there any way to do the
    validation sequentially and stop when a validation doesn’t be correct?
    an example: first => presence, second => format, third => max-length,
    fourth => uniqueness…

Last, sorry for my English :S …
Thanks!

Luis


#3

Yes, validating format only when field has a value:

ex.

validates_format_of :field, :with => “xxxx”, :allow_blank => true

:allow_nil - If set to true, skips this validation if the attribute is
nil (default is false)
:allow_blank - If set to true, skips this validation if the attribute is
blank (default is false)

or
validates_format_of :field, :with => “xxxx”, :if => Proc.new{|record|
!record.field.blank? }
but the first one is better (allow_blank), with the last one u can make
a validation based on more than one field…

Hope this helps…


#4

Amazing! thanks Gianluca :DD!!

Luis

Gianluca T. wrote:

Yes, validating format only when field has a value:

ex.

validates_format_of :field, :with => “xxxx”, :allow_blank => true

:allow_nil - If set to true, skips this validation if the attribute is
nil (default is false)
:allow_blank - If set to true, skips this validation if the attribute is
blank (default is false)

or
validates_format_of :field, :with => “xxxx”, :if => Proc.new{|record|
!record.field.blank? }
but the first one is better (allow_blank), with the last one u can make
a validation based on more than one field…

Hope this helps…