Search code examples
validationgrails

Grails validation on an associated 'hasMany' object


I'm having a validation issue very similar to what is described here

https://schneide.wordpress.com/2010/09/20/gorm-gotchas-validation-and-hasmany/

but with an important difference that I don't have (or want) a List<Element> elements field in my domain. My code is

class Location {

    static hasMany = [pocs: LocationPoc]

    Integer id
    String address
    String city
    State state
    String zip
    ...

    static mapping = {
        ...
    }

    static constraints = {  
        def regEx = new RegEx()

        address blank: true, nullable: true, matches: regEx.VALID_ADDRESS_REGEX 
        city blank: true, nullable: true 
        state blank: true, nullable: true
        zip blank: true, nullable: true
        ...
    }
}

however, if I save/update a location with a bunk POC (point of contact), I get some wild errors. I would like to validate the POC's when I save/update a location, but I'm not exactly sure how. I've tried a few variations of

pocs validator: {
    obj -> obj?.pocs?.each {
        if (!it.validate()) {
            return false
        }
    }
    return true
}

to no avail. Is this possbile without creating a new field on my domain, List<LocationPoc> pocs?


Solution

  • You're close. The issue is you need to target the property you want to validate instead of using the object reference. It should look like this:

    pocs validator: { val, obj, err ->
      val?.each {
        if (!it.validate()) return false
      }
    }