I have never tried to create global restrictions, but I can tell you that if you want to mark a field as non-empty and not null, you donโt need to create a new restriction at all, just add it to your domain class:
static constraints = { email(blank:false) }
Of course, if you expect an exception when saving, you will not get it - you need to test the object after calling save () or validate (), as shown in this domain class:
class Contact { static constraints = { name(blank:false) } String name }
and his 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 want exceptions when saving, you can add this parameter to your Config.groovy:
grails.gorm.save.failOnError = true
I found this to be very useful in development.
NTN
PS
To use the restriction that you defined, you need to add it to your domain class:
static constraints = { email(shared:"myConstraintName") }
But be careful, you cannot check the constraint in the unit test in the same way as the built-in ones, since the config will not be read.
source share