user3789902
user3789902

Reputation: 123

Fixing the grails validation error for a blank , null field in Grails

There is a domain class Person in which a field has constraint like

AnnualIncome(blank:true, nullable:true,range: 100000..100000000).

If the user does not want to fill this field then the default value of this filed is 0 and then there is a grails default exception raised which says that the value of AnnualIncome does not fall in the of 100000 to 100000000 .

But this constraints comes in use when user fills AnnualIncome field and then the range constraint is applied .But how to manage this state that the constraint is checked when user wishes to fill this detail and if he doesn't want to fill it , no exception should be raised ??

Upvotes: 1

Views: 1110

Answers (2)

cfrick
cfrick

Reputation: 37063

As you allow null set the value to null instead of 0. This makes it even easier to distinquish between a value not set or an actual 0 entered (which might change at some point in the future e.g. because you allow NPOs to register).

Otherwise you should remove the range check. If it is not relevant for storing the data, then it should be dealt with on the domain model level (GORM objects are not domain model).

Upvotes: 0

ABC
ABC

Reputation: 4373

You can use custom validator on range field for your use case:

in validator closure you can apply your constraint conditionally.

in validator closure you can check

if(AnnualIncome ==0){
    //do somthing
 }else{
   // apply constraint here.
}

Upvotes: 0

Related Questions