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
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!
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
errorsarray and return.