Grails custom validator for domain class

Aleksey picture Aleksey · Jan 18, 2011 · Viewed 7.3k times · Source

I have a restriction so there could be no more than ConfigurationHolder.config.support.reminder.web.person.max object stored. I didn't find how to add a validator which doesn't relate on particular property. So for now I implemented it in this way. Do you guys have any ideas how to make it better?

package support.reminder.web

import org.codehaus.groovy.grails.commons.ConfigurationHolder;

class Person {

    String firstName
    String lastName
    String email
    Date lastDutyDate

    static constraints = {
        firstName(blank: false)
        lastName(blank: false)
        email(blank: false, email: true)
        lastDutyDate(nullable: true)
        id validator: {val ->
        if (val)
            Person.count() <= ConfigurationHolder.config.support.reminder.web.person.max
        else
            Person.count() < ConfigurationHolder.config.support.reminder.web.person.max
    }
    }

    String toString() {
        "[$firstName $lastName, $email, $lastDutyDate]"
    }
}

Answer

david picture david · Jan 28, 2011

You can use the Grails Custom Constraints Plugin to manage your validation implementation. Then you can call your own constraint just like the predefined Grails constraints:

package support.reminder.web

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

class Person {

    String firstName
    String lastName
    String email
    Date lastDutyDate

    static constraints = {
        firstName(blank: false)
        lastName(blank: false)
        email(blank: false, email: true)
        lastDutyDate(nullable: true)
        id(maxRows: CH.config.support.reminder.web.person.max)
    }

}

Alternatively, if you don't want to rely on 3rd Party Plugins you can implement the logic of your custom validator within a Service method but call it from the custom validator in the Domain:

package support.reminder.web

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

class Person {

    def validationService
    String firstName
    String lastName
    String email
    Date lastDutyDate

    static constraints = {
        firstName(blank: false)
        lastName(blank: false)
        email(blank: false, email: true)
        lastDutyDate(nullable: true)
        id (validator: {val ->
           validationService.validateMaxRows(val, CH.config.support.reminder.web.person.max)
        }
    }

}