I ran into an instance today wherein I needed to validate that a boolean field was either true or false and not null. I tried using validates :fieldname, :presence => true, but since :presence uses #blank? under the hood, it was reading false as not being present. (Why is false considered blank?)
Anyway, I needed a validator to test whether an attribute was either true or false and I couldn’t find anything among the standard validators, so I wrote my own.
Just plop this file in your app’s lib/validators directory.
1 2 3 4 5 6 7 | |
In your model, add the validation like so:
1 2 3 4 5 6 7 | |
For more information on writing validators, see Getting Started with Custom Rails3 Validators.