【问题标题】:Grails define custom error message for command objectGrails 为命令对象定义自定义错误消息
【发布时间】:2014-02-23 17:16:15
【问题描述】:

我正在编写一个 Grails(当前为 2.3.3)应用程序并创建了一个类似于以下内容的可验证命令对象:

@Validateable
class MyCustomCommand {
  String name

  static constraints = {
    name blank: false
  }
}

在我的i18n/messages.properties 文件中,我定义了以下属性来覆盖默认错误消息。

MyCustomCommand.name.blank=Name must be provided.
MyCustomCommand.name.null=Name must be provided.

正如我所做的那样,根据 Grails 文档应该采用 [Class Name].[Property Name].[Constraint Code] 格式。当我运行我的应用程序时,如果我将值留空,我仍然会收到空属性的默认消息。

我也尝试按照默认消息的示例并将它们定义为跟随,但仍然得到默认消息。

MyCustomCommand.name.blank.message=Name must be provided.
MyCustomCommand.name.null.message=Name must be provided.

我假设我在这里遗漏了一些简单的东西,但还没有偶然发现什么。关于我做错了什么有什么建议吗?

【问题讨论】:

    标签: validation grails


    【解决方案1】:

    确实很简单。消息应如下所示:

    myCustomCommand.name.blank=Name must be provided.
    myCustomCommand.name.nullable=Name must be provided.
    
    
    //className.propertyName.blank (camelCase with first letter of class name lower)
    

    【讨论】:

    • 我相信这是我尝试的第一个变体,我刚刚尝试过,仍然得到默认值。
    • 哎呀,我在关心小写时错过了 null 部分。纠正。 :)
    【解决方案2】:

    所以,正如我所料,这很简单。我以默认值为例,它使用了null,而我真正需要的是nullable。这确实有意义,因为它与约束名称匹配。

    因此正确的版本是:

    myCustomCommand.name.blank=Name must be provided.
    myCustomCommand.name.nullable=Name must be provided.
    

    【讨论】:

      猜你喜欢
      • 2013-06-06
      • 2012-07-14
      • 2011-11-27
      • 1970-01-01
      • 2011-03-16
      • 2016-09-03
      • 1970-01-01
      • 2021-03-11
      • 2014-10-25
      相关资源
      最近更新 更多