Forum: Ruby on Rails how to validate only presence or format

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ffb15a8418eb7f49060b6764aba1dc52?d=identicon&s=25 Rm Rm (rmehta)
on 2007-02-16 07:49

 I am using following to validate the contact name like :

validates_format_of :merchant_contact_firstname, :with => /^([a-zA-Z
]+)$/, :message=>'First name is not valid.'

But it gives error even if it is left blank. Acually, it is optional but
if it is present then it can have only alphabets. How can I validate
both presence and format separately in model?

91308e9bc88cb069fd1bcf88e910d042?d=identicon&s=25 Nick Snels (nicksnels)
on 2007-02-16 08:14

I would use:

validates_format_of :merchant_contact_firstname, :if => {|c|
not c.merchant_contact_firstname.blank?}, :with => /^([a-zA-Z]+)$/,
:message=>'First name is not valid.'

Meaning that when the merchant_contact_firstname is not blank it gets
evaluated with the regex.

Kind regards,

Nick Snels
Compare Rails hosting companies
B2896675ee61d866e6a5a19407730602?d=identicon&s=25 (Guest)
on 2007-02-16 13:22
(Received via mailing list)
I believe tweaking the regexp just a little bit is easier, like this:

/^(|[a-zA-Z ]+)$/
/^([a-zA-Z ]*)$/

Judging by a quick test done in irb both seem to work just fine.

Hope it helps!

On Feb 16, 5:14 am, Nick Snels <>
This topic is locked and can not be replied to.