在Rails中自定义"密码确认与密码不匹配"

Ива*_*вац 6 ruby validation ruby-on-rails devise

有没有办法在Rails中自定义消息以确认字段?例如在设计中我必须输入密码和password_confirmation,错误信息是:

密码确认与密码不匹配

我可以更改活动记录区域设置消息("不匹配"),但它在该区域设置消息的开头和结尾输出密码确认和密码,所以我得到这样的信息:

"密码确认必须与密码匹配"

有没有办法将其更改为不同的字符串?

密码确认和密码必须匹配.

编辑

另一件事是拥有完全自定义的消息,例如:

"设置密码"和"确认密码"必须匹配.

jim*_*gic 6

ActiveRecord en.yml是我建议你想要更改Devise的验证消息的答案

这里en.yml应该是什么样的

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            email:
              blank: "Please Specify an Email id"
              taken: "Please use a different Email id"
              invalid: "Please Specify a valid Email id"
            password:
              blank: "Please Specify a Password"
              confirmation: "Password does not match"
            password_confirmation:
              blank: "Please Specify a Password Confirmation"
            first_name:
              blank: "Please Specify First Name"
            last_name:
              blank: "Please Specify Last Name"
        pdf:
          attributes:
            name:
              blank: "Please Specify name to PDF"
              taken: "Please use different name for PDF"
            attachment:
              blank: "Please Upload a PDF Attachment"
        data_element:
          attributes:
            name:
              blank: "Please give Element a desired name"
              taken: "Already Created Element with given name"
            color:
              blank: "Please assign a color to Element"
        template:
          attributes:
            name:
              blank: "Please Specify a Name"
              taken: "Please use a different name"
Run Code Online (Sandbox Code Playgroud)

我建议你定义这种方式而不是自定义设计验证模块

因为我按照上面的方法,我可能会跳过验证一两个地方

例如,删除上面的设计验证模块,然后在用户模型中替换自己的设备

然后所有的验证都会起作用,但你会错过更改密码中的验证

即使密码从未提供也从未给出,导致您登录


jim*_*gic 5

这些错误消息属于activerecord

只需创建一个具有该结构的新语言文件并替换您需要的内容。

activerecord:
  errors:
    messages:
      confirmation: "and Password must match."
Run Code Online (Sandbox Code Playgroud)

您可以为模型或模型属性定义自己的错误。 值 :model、:attribute 和 :value 始终可用于插值。

  For example,
   models:
       user:
         blank: "This is a custom blank message for %{model}: %{attribute}"
         attributes:
           login:
             blank: "This is a custom blank message for User login"
Run Code Online (Sandbox Code Playgroud)

请根据您的要求在此链接上阅读更多内容 https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml