如何针对不同的验证错误显示不同的错误消息?

时间:2015-03-07 19:51:44

标签: ruby-on-rails validation error-handling

我有一个用于获取用户手机号码的字段,因为没有人想要特定字段中的不需要的东西,我添加了验证。 这是我的验证代码

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :user_name, uniqueness: true
  validates :mobile,
                  length: {minimum: 10, maximum: 10, :message => "Just those 10 digits, thanks for the extra"},
                  :numericality => {:only_integer => true, :message => "So your number has alphabets in it?"}
end

我添加的验证是长度和数值,现在当我输入一个短于或长于10的数字时,它会显示第一个错误,但是当我添加一些字母时,它仍会显示错误的长度。

我也检查过,即使我在移动字段中输入10位数字,我仍然显示长度错误。也许我添加的验证也存在一些问题。

1 个答案:

答案 0 :(得分:0)

请澄清什么是确切的问题? 您的验证是正确的。
考虑一下我的代码:

class Comment < ActiveRecord::Base
    include ActsAsCommentable::Comment
    belongs_to :commentable, :polymorphic => true
    validates :title,
                    length: {minimum: 10, maximum: 10, :message => "Just those 10 digits, thanks for the extra"},
                    :numericality => {:only_integer => true, :message => "So your number has alphabets in it?"}
end

在控制台中输出:

comment = Comment.new
comment.title = "Long text content"
comment.valid? # false
comment.errors 
# {
#     :title => [
#         [0] "Just those 10 digits, thanks for the extra",
#         [1] "So your number has alphabets in it?"
#     ]
# }

两条错误消息都存在。