【问题标题】:Grails validation of a list objectsGrails 验证列表对象
【发布时间】:2009-06-24 19:54:39
【问题描述】:

我正在尝试让 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()

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

【问题讨论】:

    标签: grails grails-orm grails-validation


    【解决方案1】:

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

    如果是这样,您可以在您的项目约束中使用custom validator。像这样的东西(这还没有经过测试,但应该很接近):

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

    您可以比使用错误消息更有趣地在生成的错误字符串中潜在地表示哪个收件人失败,但这是执行此操作的基本方法。

    【讨论】:

    • 这确实有效,我认为我将要使用的解决方案。但是花了一些时间调试 GrailsDomainClassValidator 似乎它应该自动执行此操作并且在我的情况下不会因为休眠代理类妨碍了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    相关资源
    最近更新 更多