Ashbury
Ashbury

Reputation: 2346

Calling a specific validator on a specific attribute

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.

Upvotes: -1

Views: 100

Answers (2)

Pascal
Pascal

Reputation: 8646

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

If you want to run the validation also on createand update you can specify something like

on: [:create,:update,:preview]

(Thanks engineersmnky)

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

Upvotes: 1

Allison
Allison

Reputation: 2336

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

Upvotes: 0

Related Questions