Global Grails Restrictions

In version 1.2, Grails introduces global restrictions. I tried to add the following to Config.groovy:

grails.gorm.default = { constraints { notBlank(nullable:false, blank:false) } } 

Then, using it in one of the domain classes

 static constraints = { email(email: true, unique: true, shared: 'notBlank') } 

But when I save the user with a zero email address, error messages are not reported, why?

Thanks Don

+4
source share
2 answers

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.

+6
source

If you want the default constraint that applies to all properties should be:

 grails.gorm.default = { constraints { '*'(nullable:false, blank:false) } } 

If you want to name the restriction, you must apply it to the property of the domain class by email using the shared key:

 static constraints = { email(email: true, unique: true, shared: "notBlank") } 

The default value in grails is not to allow null properties, so blank: false is all you really need (i.e. the global default, which you defined in this case, is not required).

+2
source

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


All Articles