Tuesday, March 18, 2014

GRAILS shared / common custom validator

We can define our custom validation logic in config.groovy like below.
def dobLowerLimit = Date.parse('MM/dd/yyyy','01/01/1900')
grails.gorm.default.constraints = {
    birthDateValidator(
            validator: { value, obj ->
                if (value) {
                    if (value < dobLowerLimit) {
                        return ['past.date.error']
                    } else if (value > new Date()) {
                        return ['future.date.error']
                    }
                }
            }
    )
}

The we use it in different classes like below
class Employee {

    Date birthDate

    static constraints = {
       birthDate nullable: false, blank: false, shared: "birthDateValidator"
    }
}

class Customer {

    Date birthDate

    static constraints = {
       birthDate nullable: false, blank: false, shared: "birthDateValidator"
    }
}

No comments:

Post a Comment