簡體   English   中英

在Rails中的ruby中的每個不同的錯誤驗證中設置自定義消息

[英]set custom message in each different error validation in ruby on rails

可以說我已經在模型中設置了這樣的驗證

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

如何在每次驗證的視圖中顯示自定義消息。

當我在視圖頁面中設置它時。

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

它直接顯示所有錯誤消息。 我想這樣顯示

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

我可以這樣嗎?

您可以為每個驗證器在單獨的哈希中傳遞message

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

閱讀有關狀態長度數字驗證器的更多信息。

一種實現方法是為每種類型的驗證(在模型中)定義方法,如下所示:

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

等等...

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM