执行一个验证只有当所有其他校验通过 [英] perform one validation only if all other validations pass

查看:110
本文介绍了执行一个验证只有当所有其他校验通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个自定义的验证,检查一个的银行账号排序code 的与外部API,如果它们存在测试(即是一个正确的有效的英国银行账户)。由于这是一个昂贵的操作,我不想打扰击中API,除非账号和排序code通Rails的内置的验证。

I am building a custom validation that checks a bank account number and sort code with an external API to test if they exist (i.e. is a proper valid UK bank account). As this is an expensive operation I don't want to bother hitting the API unless the account number and sort code pass Rails' built in validations.

例如,我有这些基本的验证:

For example, I have these basic validations:

validates_presence_of :sort_code, :account_number
validates_format_of :sort_code, :with => Regexes::SORT_CODE
validates_format_of :account_number, :with => Regexes::ACCOUNT_NUMBER

然后,我有我的自定义验证:

Then I have my custom validation:

validate :check_valid_bank_account

def check_valid_bank_account
  # code here is irrelevant, but essentially this hits the API
  # if it's a valid UK bank account all is OK, if not we add an error
end

我想要确保的是,如果该模型的其余部分有效时,才执行自定义验证。只需支付25便士被告知未提供账号时,我可以工作了这一点喽!

What I want to ensure is that the custom validation is only performed if the rest of the model is valid. No point paying 25p to be told no account number was provided when I can work that out myself!

我知道我可以写一些逻辑来检查,这两个属性不为空,反对手动正则表达式匹配他们......但这似乎不是很Rails的方式。

I am aware I could write some logic that checks that the two attributes are not blank and matches them against the regex manually... but that doesn't seem a very Rails way.

推荐答案

您可以检查错误阵列和回报。

You could check the errors array and return.

def check_valid_bank_account
  return unless errors.blank?
  …
end

这篇关于执行一个验证只有当所有其他校验通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆