Grails验证列表对象

Gar*_*vis 4 grails grails-orm grails-validation

我试图获取grails来验证对象列表的内容,如果我首先显示代码可能会更容易:

class Item {
  Contact recipient = new Contact()
  List extraRecipients = [] 

  static hasMany = [
          extraRecipients:Contact
  ]

  static constraints = {}

  static embedded = ['recipient']
}

class Contact {
  String name
  String email

  static constraints = {
    name(blank:false)
    email(email:true, blank:false)
  }
}    
Run Code Online (Sandbox Code Playgroud)

基本上我所拥有的是一个必需的联系人('收件人'),这很好用:

def i = new Item()
// will be false
assert !i.validate() 
// will contain a error for 'recipient.name' and 'recipient.email'
i.errors 
Run Code Online (Sandbox Code Playgroud)

我还要做的是验证Contact'extraRecipients'中的任何附加对象,以便:

def i = new Item()
i.recipient = new Contact(name:'a name',email:'email@example.com')

// should be true as all the contact's are valid
assert i.validate() 

i.extraRecipients << new Contact() // empty invalid object

// should now fail validation
assert !i.validate()
Run Code Online (Sandbox Code Playgroud)

这是可能的还是我只需要在我的控制器中迭代集合并调用validate()每个对象extraRecipients

Ted*_*eid 9

如果我正确理解了这个问题,你希望错误出现在Item域对象上(作为extraRecipients属性的错误,而不是让级联保存在extraRecipients中的各个Contact项上抛出验证错误,对吧?

如果是这样,您可以在Item约束中使用自定义验证器.像这样的东西(这还没有经过测试但应该接近):

static constraints = {
    extraRecipients( validator: { recipients ->
        recipients.every { it.validate() } 
    } )
}
Run Code Online (Sandbox Code Playgroud)

您可以获得比错误消息更好的可能在结果错误字符串中表示哪个收件人失败,但这是执行此操作的基本方法.