我正在尝试使用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)
}
}
基本上我拥有的是一个必需的联系人('收件人'),这很好用:
def i = new Item()
// will be false
assert !i.validate()
// will contain a error for 'recipient.name' and 'recipient.email'
i.errors
我还要做的是验证'extraRecipients'中任何附加的Contact
对象,以便:
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()
这是可能的还是我只需要在我的控制器中迭代集合并在validate()
中的每个对象上调用extraRecipients
?
答案 0 :(得分:8)
如果我正确理解了这个问题,你希望错误出现在Item域对象上(作为extraRecipients属性的错误,而不是让级联保存在extraRecipients中的各个Contact项上抛出验证错误,正确?
如果是这样,您可以在商品约束中使用custom validator。这样的事情(这还没有经过测试但应该接近):
static constraints = {
extraRecipients( validator: { recipients ->
recipients.every { it.validate() }
} )
}
您可以获得比错误消息更好的信息,以便在收件人失败的结果错误字符串中潜在地表示,但这是执行此操作的基本方法。