I only want to validate when field is not empty

Hi,

I have a field in my user model:

<p><label for="user_work_phone">Work phone</label><br/> <%= text_field 'user', 'work_phone' %></p>

But I only want to validate it if it is non-empty. So I put this into my user model:

  validates_as_phone :work_phone, :if => !:work_phone.blank? && :is_client?, :message => "is not a valid phone number"

But if I leave the field blank and submit the form, the form is returned to me with the message "Work phone is not a valid phone number:". What is wrong with the above statement?

Thanks, - Dave

Try :allow_nil => true

Peace, Phillip

Thanks. It's still not working but I'm using a "validate_as_phone" plugin

  validates_as_phone :work_phone, :allow_nil => true, :message => "is not a valid phone number"

How did you envision doing this without such a plug-in? Best, - Dave

Didn't see that as a plugin. Sorry. It seems that the plugin would need to support blank values.

Apart from using the plugin, I guess you could use some regex. Look in the plugin to see how it's done. You could probably just create your own private method in the class to handle it. Or, you might be able to extend the plugin.

Peace, Phillip

Not used the validates_as_phone plugin before, but looking at the source for validates_as_phone, it is only allowing lengths of 7, 10 and 11 for the string length. You could either 'monkey patch' the plugin to do what you want (e.g. accept string length of 0), or use the plugin's code as a base for writing your own validation plugin.

Rails 2 also has an allow_blank property for validations but i'm not sure if this would be supported by this custom plugin. I can't see anywhere in the code where it would check this explicitly but you could try this if you are on v2. allow_nil will only validate if the actual value from the parameters hash is nil, not if it is ""

The plugin doesn't really look too amazing, to be honest, It only strips out any non-numeric characters and checks for length. Sure that US phone numbers are more complex than that! It is also not very optimised, calling the same methods several times (namely new_value.length) instead of storing this computation in a variable.

Good luck joe

Thanks for this feedback. I am very open to using other methods of validating US phone numbers, I just happened to find this one in a Google search. What do you use? - Dave