Search code examples
ruby-on-rails-3.1

validate hardcoded value in rails model


I have a registration form where user has to enter his credentials plus a textfield called as promotion code. So the form can be submitted only when the promotion code's value is "akpoi". So the user has to enter this string for form submission, Otherwise it would display error message to user as "akpoi should be entered in promotional code field". How do I check this in rails model validation??


Solution

  • This should be check on the controller side

    if params[:field_name] == "akpoi"
    
    else
    
    end
    

    If u insist to do it in model do following

    after_validation :check_field_value
    
    def check_field_value
      self.errors.add(:comment, "Add Your Error Here") if field_name != "akpoi"
    end