Grails global constraints

grails, grails-orm

Solution

I've never tried to make global constraints, but I can tell you that if you want to mark a field as not blank and not nullable you don't need to create a new constraint at all, just add this to your domain class:

static constraints = {
    email(blank:false)
}

Of course if you're expecting an exception on save you won't get one - you need to test the object after calling save() or validate() as demonstrated in this domain class:

class Contact {
    static constraints = {
        name(blank:false)
    }
    String name
}

and its test case:

import grails.test.*

class ContactTests extends GrailsUnitTestCase {
    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testNameConstraintNotNullable() {
        mockDomain Contact
        def contact = new Contact()
        contact.save()
        assertTrue contact.hasErrors()
        assertEquals "nullable", contact.errors["name"]
    }
}

If you do want exceptions on save, you can add this setting in your Config.groovy:

grails.gorm.save.failOnError = true

I found it to be quite useful in development.

HTH

PS

To use a constraint you've defined you'd need to add this to your domain class:

static constraints = {
    email(shared:"myConstraintName")
}

But be warned, you can't test the constraint in a unit test as you would the built in ones as the config will not have been read.

Problem

In version 1.2, Grails introduced global constraints. I tried adding the following to Config.groovy ``` grails.gorm.default = { constraints { notBlank(nullable:false, blank:false) } } ``` Then using it in one of my domain classes ``` static constraints = { email(email: true, unique: true, shared: 'notBlank') } ``` But when I save a user with a null e-mail address, no errors are reported, why? Thanks, Don

Original source