How to validate not blank attributes only?

Nanyang Zhan wrote:

I created a form to edit user's information. In the form there are fields that are optional to fill, like phone number. I use some Rails' validations to validate the form, intending to filter any bad information when user DO enter something. One of these validations is validates_numericality_of :phone

now the problem is: when the phone number field is left blank, which is acceptable by me, Rails jumps out and says "Phone is not a number".

So, how to validate not blank attributes only?

You can use the validate method within the user model like is shown at the top of ActiveRecord::Validations You can then use a regular expression or manually check to see if the phone number meets your requirements.

Matthew Margolis blog.mattmargolis.net

Nanyang Zhan wrote:

Thank, Matthew I thought there were a simpler solution, like adding a option :allow_nil => true But why no?

Matthew Margolis wrote:   

You can use the validate method within the user model      Using allow_nil should do the trick as well. If you would prefer you can use validates_format_of and a regular expression to match a 0 length string or a string of numbers with phone number formatting agents like dashes or parenthesis.

Matthew Margolis blog.mattmargolis.net