简体   繁体   中英

Rails model conditional vaidation

I validate fields in model using:

validates :first_name, :presence => true, :if => :should_validate?
validates :last_name, :presence => true, :if => :should_validate?
...

There are many fields in model that needs to be validated and it doesn't look good if I specify:if => method for each one.

Is it possible to embed this validates methods in block instead of giving:if => method for each one?

You could write your own custom validator of course, but if you're only validating presence, this might do the trick:

validates :first_name, :last_name, :presence => true, :if => :should_validate?

I don't think there is something out of the box for this. If you want, you can use a custom validator.

What are the conditions that you need this validated? If you don't need it validated couldn't you just leave that line out? Otherwise you could just validate on certain actions so you don't need to evaluate for should_validate?, for example:

validates :first_name, :last_name, :presence => true, :only => [:create, :update]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM