Home > Software engineering >  Calling a specific validator on a specific attribute
Calling a specific validator on a specific attribute

Time:01-27

I defined a custom EachValidator to see if an attribute has leading or trailing whitespace. I know you can add it to the model like so:

validates :name, whitespace: true

But in the controller I want to call just run just the whitespace validator for some form feedback.

I can run it like this:

Validators::WhitespaceValidator.new(attributes: :name).validate_each(obj, :name, obj.name)

Is there a shorter way to call the specific validator? Like you can do user.valid? but that runs all of the validations. I only want the whitespace validator on the name attribute.

CodePudding user response:

This feels like trying to solve a problem (leading/trailing whitespace) by creating a new problem (rejecting the object as invalid), and I agree with the comment about this being a brittle strategy. If the problem you want to solve here is whitespace, then solve that problem for the specific attributes where it matters before saving the object; check out Rails before_validation strip whitespace best practices

CodePudding user response:

Since you did not come here to be told that your idea is bad and people will hate it: here is an idea that you can play with: :on

https://guides.rubyonrails.org/active_record_validations.html#on

validates :name, whitespace: true, on: :preview

and then in the controller:

def something
  @model.valid?(:preview)
end

I guess you'd need to define ithe whitespace part twice, once for :preview and once for normal validation/save.

Also: I don't think that giving early feedback to users, before they actually save the record is a bad idea if properly implemented.

  • Related