简体   繁体   中英

set custom message in each different error validation in ruby on rails

let say that I have set in model for validation like this

validates :tel, presence: true , length: { minimum: 10,  maximum: 11 }, numericality: { only_integer: true }

how do I can display a custom message in view for each validate.

when I set this in views page.

<% if @diary.errors.include?(:tel) %>    
      <div class="err"><p><%= @diary.errors.full_messages_for(:tel).join("") %></p></div>
<% end %>

it directly displays all error message. I want to make a display in view like this

if(error_require)
   echo "tel is needed"
else if(error_length)
   echo "tel is to long"
else 
   echo "tel must numeric"
end

can I make like that?

You can pass message in separate hashes for each validator:

validates :tel,
          presence: { message: 'is needed' },
          length: { minimum: 10, maximum: 11, too_long: 'is too long' },
          numericality: { only_integer: true, message: 'must be numeric' }

Read more about presence , length , and numericality validators.

One way to do this is to define methods for each type of validation (in your model) like this:

validate :chech_length

def chech_length
  if tel.length < 10 || tel.length > 11

      errors.add(:base, "tel is too long!") 
   end
end



validate :check_if_present

def check_if_present

  if tel.blank?
     errors.add(:base, "tel must be present!")
  end
end

etc...

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM