2014-09-19 57 views
0

假设我有一些领域类使用默认的验证:定制验证消息

class Employee { 

     String name 
     String primaryEmail 
     String url 

     static constraints = { 
      name blank: false 
      primaryEmail email: true, unique: true 
      url blank: false, url: true 

     } 

    } 

我想定义应在验证失败的情况下返回的消息,类似的东西的名称:

class Employee { 

     String name 
     String primaryEmail 
     String url 

     static constraints = { 
      name blank: false 'employee.invalid.name' 
      primaryEmail email: true, unique: true 
      url blank: false, url: true 'employee.invalid.email' 

     } 

    } 

有没有可能以某种方式?谢谢!

回答

1

定义您自己的自定义消息其实很简单。但是,您的方法不正确。

首先,看看validation reference了解验证消息代码是如何构建的。使用

你的榜样,一些自定义的消息是:

employee.name.blank=Custom message about invalid employee due to blank 
employee.url.blank=Another custom message about blank url 
employee.url.url.invalid=Custom invalid url message 

消息是每个约束类型,因此具有每个属性一个全局消息行不通的。您需要为每个可能失败的约束提供消息。

1

您可以通过定义自定义验证器来完成此操作。它基本上是一个关闭,最多需要三个参数。因此,在您例如,你可以写:

class Employee { 

    String name 
    String primaryEmail 
    String url 

    static constraints = { 
     name validator: { 
      if (!it) return ['employee.invalid.name'] 
     } 
     primaryEmail email: true, unique: true 
     url validator: { 
      if (!it) return ['employee.invalid.email'] 
     } 
    } 

}

备注自定义的验证关闭:如果没有提供,那么你可以用隐含它变量属性的访问值PARAMS:

validator: { 
    if (!it) ... 
} 

如果您提供了两个参数,那么第一个参数是属性值,第二个是正在验证的域类实例(例如,您可以检查其他参数)

validator: {val, obj -> 
    if (val && obj.otherProp){...} 
} 

如果您提供三种PARAMS那么前两个是相同的两个参数版本,三是春节错误对象:

validator: {val, obj, err -> 
    if (val && obj.otherProp){...} 
} 

如需更详细的说明请查看文档: http://grails.org/doc/latest/ref/Constraints/validator.html