I have a form for creating a place. Depending on the country, the province field (state, region) is required or not.
When not required, I want to be empty, not empty. I have code that makes all empty form fields null:
def newparams = [:] place = new Place() params.each() { k, v -> if (v instanceof String && place.hasProperty(k)) { if (!v.trim().length()) { newparams[k] = null } else { newparams[k] = v } } } place = new Place(newparams) place.validate()
Now, in the domain domain, I have a validator in the province:
province validator: {val, obj -> if (obj.country in obj.requiresRegionCountries() && !obj.province) return [province.required]}
With this rule, I always get "the province cannot be zero", even if it is required or not.
I think this is because the nullable validator, which is set to false by default.
If I add a nullable: true value, then even if a province is required, the custom validator is skipped and it can be saved with an empty province (I think this is because it is created using null)
Now I need to somehow configure my validator and also indicate the nullable value in my validator, something like this:
province validator: {val, obj -> if (obj.country in obj.requiresRegionCountries() && !obj.province) { nullable: false return [province.required] } else { nullable: true } }
How can I achieve this in Grails 2.0.3?