r4cc00n
r4cc00n

Reputation: 2137

How to check if a specific attribute is valid ruby on rails

I have been looking for an out-of-the-box way to check if a specific attribute is valid for a certain model but I haven't found anything, I think is weird that rails do not provide a very easy way to check this.

note: I don't want to use valid? because that will run all the validations in my model. Let me know if I am missing anything, thanks in advance.

Upvotes: 2

Views: 1537

Answers (2)

Fabien
Fabien

Reputation: 427

To me, the quickest solution to check one attribute would be:

user = User.new(email: 'wrongEmail')
user.validate(:email) => false or true

Upvotes: 1

r4cc00n
r4cc00n

Reputation: 2137

After looking for a couple of hours, I didn't find anything specific but I did come with a workaround to the problem. Let's say you have a model called User (which is quite common) and you want to validate that the email complies with the validations you have in place, below is a way to check only for that specific attribute.

user = User.new(email: 'foo!!!')
User.validators_on(:email).map{ |validator| validator.validate(user) } # apply the validator to the attribute
user.errors.full_messages # will return a list of all the errors found with the specified attribute

Upvotes: 3

Related Questions