Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 411
r4cc00n Avatar asked Jan 25 '26 09:01

r4cc00n


1 Answers

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
like image 104
r4cc00n Avatar answered Jan 26 '26 23:01

r4cc00n