Grails custom validator for domain class

I have a limitation, so the ConfigurationHolder.config.support.reminder.web.person.maxobject can no longer be saved. I have not found how to add a validator that does not apply to a specific property. So now I implemented it that way. Do you have any idea how to do this 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]"
    }
}
+3
source share
3 answers

You can use the Grails Custom Constraints plugin to manage your validation implementation. You can then call your constraint in the same way as Grails predefined 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)
    }

}

, , , :

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

}
+5

, , , , , < =. , , Person.count(). , <= , , , .

0

, ​​ personService.addPerson(). . , , , , .

Using a validator to limit the number of objects is actually not very good if relative to the validator value: the object is valid, only the number of objects is too large.

In short: the logic code goes to the service.

0
source

Source: https://habr.com/ru/post/1786154/


All Articles