I am a beginner at ruby on rails. I am trying to add an error, only if multiple validations fail.
My initial idea is to use multiple unless with or operator.
class SomeValidator
def validate(record)
unless code.match(some_regex) || code.match(some_other_regex) || code.match(some_other_regex)
add error
end
end
end
it just doesn't seem right.
If I validate each validation separated, the validation will fail before the next one.
I don't know if it is clear, I want to see a way to for example, validate a string to four different regexes, and add an error if all four regexes fail.
CodePudding user response:
If you want to only execute some piece of logic if all four conditions fail, you'll want to use &&
(logical and
) and not ||
(logical or
)
CodePudding user response:
You could use Array#none?
it should return true if all elements are false. for example:
add error if [condition_1, condition_2, condition_3].none?
Or as mentioned by @inyl
add error unless condition_1 && condition_2 && condition_3
unless
is confusing, I would avoid it for complex conditions.