【问题标题】:Form validation message with aliased attribute name具有别名属性名称的表单验证消息
【发布时间】:2014-04-19 14:33:04
【问题描述】:

我在模型类中使用 Stripe。我有一个 strike_token 属性,我正在验证它的存在并创建一个自定义消息,如下所示:

validates :stripe_token, presence: { message: 'Please enter valid card info' }

当表单提交无效时,错误信息是“Stripe token Please enter valid card info”

我不希望错误消息中出现 Stripe 令牌。我还有其他适合默认的验证,所以我不想更改默认的错误行为。

如果我可以将 Stripe 令牌属性别名为 :card_info 之类的东西,而实际上并没有将其作为模型上的属性,那就更好了。

因此可以将消息设为“卡信息不能为空”

【问题讨论】:

    标签: ruby-on-rails validation


    【解决方案1】:

    您可以按照以下方式进行:

    只需从验证中删除 :message 部分。

    # config/locales/en.yml
    en:
      activerecord:
        attributes:
          model_name:
            stripe_token: ""
        errors:
          models:
            model_name:
              attributes:
                stripe_token:
                  blank: "Card info cannot be blank!"
    

    # config/locales/en.yml
    en:
      activerecord:
        attributes:
          model_name:
            stripe_token: "Card info"
        errors:
          models:
            model_name:
              attributes:
                stripe_token:
                  blank: " cannot be blank!"
    

    model_name 替换为您的小写字母型号名称。详情请查看Fully custom validation error message with Rails

    更新

    # config/locales/en.yml
        en:
          activerecord:
            attributes:
              model_name:
                stripe_token: "Card info"
    

    然后使用,

    validates :stripe_token, presence: { message: ' cannot be blank!' }
    

    希望对你有帮助:)

    【讨论】:

    • 更改属性名称有效,但我更愿意在模型验证本身上设置消息。喜欢validates :stripe_token, presence: { message: 'cannot be blank!' } 然后我会接受你的回答
    • 是的,我认为这是可能的。请在我的回答中查看更新。
    猜你喜欢
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 2020-06-18
    • 2014-11-25
    相关资源
    最近更新 更多