Grails的验证对象

问题描述:

我试图让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 

我想什么也看它验证任何附加Contact对象的“extraRecipients”这样的:

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() 

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

如果我理解正确的问题,你希望出现在错误的项目域对象(作为extraRecipients属性是一个错误,而不是让级联保存扔在extraRecipients个人联系人项目验证错误?,右

如果是这样,你可以在你的项目限制使用custom validator像这样的东西(这还没有经过测试,但应接近):

static constraints = { 
    extraRecipients(validator: { recipients -> 
     recipients.every { it.validate() } 
    }) 
} 

你可以得到比用票友错误消息可能表示错误字符串中的哪个收件人失败,但是这是做这件事的基本方式。

+0

谢谢我在今晚晚些时候会有一个bash – 2009-06-25 11:37:18