5

使用命令对象时,例如:

class UserCommand {

   String name

   static constraints = {
      name blank: false, unique: true, minSize: 3
   }
}

您可以使用它们来验证对象而不使它们持久化。就我而言,我将验证持久类用户。

在控制器中:

def save(UserCommand cmd) {
  if(!cmd.validate()) {
      render view: "create", model: [user: cmd]
  return
  }
  def user = new User()
  user.name = cmd.name
  user.save()

  redirect uri: '/'

} 

在messages.properties中:

user.username.minSize.error=Please enter at least three characters.
userCommand.username.minSize.error=Please enter at least three characters.

使用自定义验证消息时,您必须为每个错误编写两次消息代码。一个用于 User 类,另一个用于 UserCommand 类。

有没有办法让每个错误只有一个消息代码?

4

2 回答 2

5

我在这里可能是错的,但如果你只使用股票 Grails 约束,共享验证消息的唯一方法是简单地依赖default.x.x.message于messages.properties 中的键/值。否则,将通过以下密钥形式查找消息:

className.propertyName.errorcode...=

但是,您可以使用自定义验证器并覆盖为验证错误返回的消息密钥。

class User {
  ...

  static constraints = {
    ...
    name blank: false, unique: true, validator: { value, user ->
      if(!value || value.length() < 3)
        return 'what.ever.key.in.messages.properties'
    }
  }
}

然后,您可以通过全局约束或@dmahapatro 提到的在类之间共享约束来保持所有内容干燥,importFrom就像这样在 UserCommand 中使用,

class UserCommand {
 ...
 static constraints = {
   importFrom User
   ...
  }
}

如果您有更复杂的验证,您可以创建自己的约束类。以下是一些资源:

http://www.zorched.net/2008/01/25/build-a-custom-validator-in-grails-with-a-plugin/ http://blog.swwomm.com/2011/02/custom- grails-constraints.html

于 2013-06-11T11:00:56.290 回答
2
  1. using unique constraint in CommandObject makes no sense, because uniqueness of what would it check?
  2. you can validate domain objects without persisting them exactly the same way as command objects - using validate() method
  3. you can put a User object in command object, set constraints only for the domain class, and then validate User object being a part of command object

    class User { 
        String name
        static constraints = {
            name blank: false, unique: true, minSize: 3
        }
    }
    
    class UserCommand {
        User user 
        static constraints = {
            user validator: { it.validate() }
        }
    }
    
    user.username.minSize.error=Please enter at least three characters.
    
于 2013-06-10T22:50:11.920 回答