Grails 验证列表对象
我正在尝试让 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 protected]')
// 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
中的每个对象上?
I'm trying to get grails to validate the contents of a List of objects, might be easier if I show the code first:
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)
}
}
Basically what i have is a single required Contact ('recipient'), this works just fine:
def i = new Item()
// will be false
assert !i.validate()
// will contain a error for 'recipient.name' and 'recipient.email'
i.errors
What I'd like also do it validate any of the attached Contact
objects in 'extraRecipients' such that:
def i = new Item()
i.recipient = new Contact(name:'a name',email:'[email protected]')
// 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()
Is this possible or do I just have to iterate over the collection in my controller and call validate()
on each object in extraRecipients
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解了这个问题,您希望错误出现在 Item 域对象上(作为 extraRecipients 属性的错误,而不是让级联保存在 extraRecipients 中的各个联系人项目上引发验证错误,对吗?
如果因此,您可以在 Item 约束中使用 自定义验证器。像这样的东西(尚未经过测试,但应该接近):
您可以使用比错误消息更奇特的方法来潜在地在结果错误字符串中指示哪个收件人失败,但这是执行此操作的基本方法。
If I'm understanding the question correctly, you want the error to appear on the Item domain object (as an error for the extraRecipients property, instead of letting the cascading save throw a validation error on the individual Contact items in extraRecipients, right?
If so, you can use a custom validator in your Item constraints. Something like this (this hasn't been tested but should be close):
You can get fancier than that with the error message to potentially denote in the resulting error string which recipient failed, but that's the basic way to do it.