0

I'm trying to validate 4 fields with the same validation on the user model as they sign up. I don't want to have to write 4 different methods with the same logic.

I'm validating the following fields first_name, last_name, user_name and nickname. This is what I'm checking

 def validate_input 
   if first_name.present? && first_name.start_with?("=", "@", "-", "+")
    first_name.prepend('`')
   end
 end

How can I go about this method without having to repeat myself 4 times with the same method?

1
  • 2
    guides.rubyonrails.org/… You can either use a simple method (see 6.2 Custom Methods) or write a full-on validator (6.1). 6.2 might be easier. That said: this isn't a validation, this is a modification, so I'm not sure this would be the right thing to do anyway. Commented Mar 11, 2021 at 20:42

1 Answer 1

3

I think you are not validating the fields. Instead, you are modifying them. So, the logic should go into the callback.

before_save :sanitize_the_names

def sanitize_the_names
  [:first_name, :last_name, :user_name, :nickname].each do |field|
    self.public_send(field).prepend('`') if field_invalid?
  end
end

def field_invalid?
  self.public_send(field).present? && self.public_send(field).start_with?('=', '@', '-', '+')
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.