Grails custom validator for domain class

空扰寡人 提交于 2019-12-04 13:08:24

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

}

I don't have a better idea, but I do suggest that maybe you need to check for < not <=. I think that when validating your object, it has not yet been stored in the DB, so it will not be included in Person.count(). I reckon that <= would cause it to pass the validation then be saved, then you would be violating the rule.

I recommend you using a service function, like personService.addPerson(). Then check the constraint before you save a new object. It will benefit if you get more complicated constraint, such as when it related many domain objects, for example.

The use of a validator for restricting the number of object is actually not very good if concerning about the meaning of validator: the object is valid, only the number of objects is too large.

In short: the logical code goes to the service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!