Grails default nullable constraints - validation

In my Grails app I have the following command object
#Validateable
class CalendarEventCommand {
#BindingFormat('FestivalType')
Collection<FestivalType> types
Date start
Date end
MapFocalPoint location
boolean freeOnly = false
}
which is used as the argument to a controller action
def getCalendarEvents(CalendarEventCommand calendarEventCommand) {
if (calendarEventCommand.validate()) {
log.error "Command errors $calendarEventCommand.errors"
} else {
log.warn "Everything is fine"
}
}
In Config.groovy I've specified the following as the default constraints
grails.gorm.default.constraints = {
// apply a max size of 191 chars to String columns to support utf8mb4
// http://mathiasbynens.be/notes/mysql-utf8mb4
'*'(maxSize: 191)
// this shared constraint provides a way to override the default above for long text properties
unlimitedSize(maxSize: Integer.MAX_VALUE)
}
If an instance is created with a null value for start and end validation passes, but I wouldn't expect it to because AFAIK a default constraint of nullable: false should be applied to all properties. I've tried adding this explicitly, by changing the first default constraint to
'*'(maxSize: 191, nullable: false)
But validate() still returns true when start and/or end are null. If I add these constraints to CalendarEventCommand
static constraints = {
start nullable: false
end nullable: false
}
then validate() returns false, but AFAIK it shouldn't be necessary for me to add these constraints.

I think this is an expected behavior. There are couple of JIRA defects regarding this functionality out of which GRAILS-7431 and GRAILS-8583 seems more focused towards the behavior.
I was going through DefaultConstraintEvaluator.java which takes care of global constraints only for domain classes. I think we have to end up using the way mentioned later.
static constraints = {
start nullable: false
end nullable: false
}

Related

Validate nested domain class instance in command object

I try to validate a nested domain class instance on a command object.
Having the following command object
package demo
import grails.databinding.BindingFormat
class SaveEventCommand {
#BindingFormat('yyyy-MM-dd')
Date date
Refreshment refreshment
static constraints = {
date validator: { date -> date > new Date() + 3}
refreshment nullable: true
}
}
And having the following domain class with its own constraints
package demo
class Refreshment {
String food
String drink
Integer quantity
static constraints = {
food inList: ['food1', 'food2', 'food3']
drink nullable: true, inList: ['drink1', 'drink2', 'drink3']
quantity: min: 1
}
}
I need when refreshment is not nullable the command object validates the date property and check the corresponding restrictions in refreshment instance
For now try with this code in the controller:
def save(SaveEventCommand command) {
if (command.hasErrors() || !command.refreshment.validate()) {
respond ([errors: command.errors], view: 'create')
return
}
// Store logic goes here
}
Here through !command.refreshment.validate() I try to validate the refresh instance but I get the result that there are no errors, even when passing data that is not correct.
Thank you any guide and thank you for your time
I typically just include some code that will use a custom validator to kick off validation for any property that is composed of another command object. For example:
thePropertyInQuestion(nullable: true, validator: {val, obj, err ->
if (val == null) return
if (!val.validate()) {
val.errors.allErrors.each { e ->
err.rejectValue(
"thePropertyInQuestion.${e.arguments[0]}",
"${e.objectName}.${e.arguments[0]}.${e.code}",
e.arguments,
"${e.objectName}.${e.arguments[0]}.${e.code}"
)
}
}
})
This way it's pretty clear that I want validation to occur. Plus it moves all the errors up into the root errors collection which makes things super easy for me.
Two things I could think of:
Implement grails.validation.Validateable on your command object
What happens when you provide an invalid date? Can you see errors while validating?

Grails command object validation gives exception instead of errors

I have command object like this:
#Validateable
class TaCustomerBoardActionCommand {
TaCustomerBoardAction action
static constraints = {
action casecade: true
}
}
and classes in command object below:
class TaCustomerBoardAction {
TaCustomerBoard taCustomerBoard
TaapAction taapAction
Date dateCreated // updated by grails
Date lastUpdated // updated by grails
User createdBy
OrgUnit orgUnit
Client client
static belongsTo = [Client]
static constraints = {
}
}
and
TaapAction {
int id
User createdUser
User responsibleUser
Brand brand
BusinessType businessType
Topic topic
Topic subTopic
String subject
String description
Date targetDate
int progress
String responsible
Client client
static belongsTo = [Client]
OrgUnit orgUnit
Date dateCreated // updated by grails
Date lastUpdated // updated by grails
TaapActionState taapActionState
static constraints = {
subject nullable: false, size: 1..64
description nullable: false, size: 1..4000
responsible nullable: false, size: 1..512
progress nullable: false
responsibleUser nullable:false
brand nullable:false
businessType nullable:false
topic nullable:false
subTopic nullable:false
targetDate nullable:false
}
TaCustomerBoard has similar constraints as above class.
but it gives exception instead of error codes.
Below is controller Post method:
def saveTaCustomerBoardAction(TaCustomerBoardActionCommand cmd){
if(cmd.validate()){
taActionPlanningService.saveAction(cmd.action.taapAction)
cmd.action.save(flush: true, failOnError: true)
}
[cmd:cmd]
}
Stack trace:
grails.validation.ValidationException: Validation Error(s) occurred
during save():
- Field error in object 'de.idare.move.taap.TaapAction' on field 'progress': rejected value [null]; codes
[de.idare.move.taap.TaapAction.progress.typeMismatch.error,de.idare.move.taap.TaapAction.progress.typeMismatch,taapAction.progress.typeMismatch.error,taapAction.progress.typeMismatch,typeMismatch.de.idare.move.taap.TaapAction.progress,typeMismatch.progress,typeMismatch.int,typeMismatch];
arguments [progress]; default message [Data Binding Failed]
- Field error in object 'de.idare.move.taap.TaapAction' on field 'description': rejected value [null]; codes
[de.idare.move.taap.TaapAction.description.nullable.error.de.idare.move.taap.TaapAction.description,de.idare.move.taap.TaapAction.description.nullable.error.description,de.idare.move.taap.TaapAction.description.nullable.error.java.lang.String,de.idare.move.taap.TaapAction.description.nullable.error,taapAction.description.nullable.error.de.idare.move.taap.TaapAction.description,taapAction.description.nullable.error.description,taapAction.description.nullable.error.java.lang.String,taapAction.description.nullable.error,de.idare.move.taap.TaapAction.description.nullable.de.idare.move.taap.TaapAction.description,de.idare.move.taap.TaapAction.description.nullable.description,de.idare.move.taap.TaapAction.description.nullable.java.lang.String,de.idare.move.taap.TaapAction.description.nullable,taapAction.description.nullable.de.idare.move.taap.TaapAction.description,taapAction.description.nullable.description,taapAction.description.nullable.java.lang.String,taapAction.description.nullable,nullable.de.idare.move.taap.TaapAction.description,nullable.description,nullable.java.lang.String,nullable];
arguments [description,class de.idare.move.taap.TaapAction]; default
message [Property [{0}] of class [{1}] can not be null]
Kindly help me I am stuck with this problem.
Your problem is rather straight forward. Well it would seem, you have provided how things work but not actually provided what is sent. My suggestion is to do a println params in the controller action using validation method to see what it is sent / and validated.
You have declared progress as int and not Integer. This means it can't be nullable. Always use Boolean Integer or whatever the case maybe if something is meant to be nullable. Secondly you have also declared description and progress as nullable false meaning they have to be provided. The error message suggests command sent does not have a progress or description sent to it as part of the validation. This is something you need to investigate further by simple debugging such as println at your end to figure out why that is the case.
int progress
...
static constraints = {
progress nullable: false
description nullable: false, size: 1..4000
}
Just remove the failOnError: true. You'll be able to process error objects instead of catching exception.
Documentation

Grails validation on an associated 'hasMany' object

I'm having a validation issue very similar to what is described here
https://schneide.wordpress.com/2010/09/20/gorm-gotchas-validation-and-hasmany/
but with an important difference that I don't have (or want) a List<Element> elements field in my domain. My code is
class Location {
static hasMany = [pocs: LocationPoc]
Integer id
String address
String city
State state
String zip
...
static mapping = {
...
}
static constraints = {
def regEx = new RegEx()
address blank: true, nullable: true, matches: regEx.VALID_ADDRESS_REGEX
city blank: true, nullable: true
state blank: true, nullable: true
zip blank: true, nullable: true
...
}
}
however, if I save/update a location with a bunk POC (point of contact), I get some wild errors. I would like to validate the POC's when I save/update a location, but I'm not exactly sure how. I've tried a few variations of
pocs validator: {
obj -> obj?.pocs?.each {
if (!it.validate()) {
return false
}
}
return true
}
to no avail. Is this possbile without creating a new field on my domain, List<LocationPoc> pocs?
You're close. The issue is you need to target the property you want to validate instead of using the object reference. It should look like this:
pocs validator: { val, obj, err ->
val?.each {
if (!it.validate()) return false
}
}
Validation doesn't automatically cascade through hasMany associations. In order to get free validation, the other side of the relationship needs to belong to Location.
You didn't include your LocationPOC class, but if you modify
Location location
to
static belongsTo = [location: Location]
Then you will get cascading validation when you save your Location object.
If you can't set the belongsTo property on LocationPoc, and need to use the custom validator, the syntax is a bit different than the answer above.
pocs validator: {val, obj ->
val?.inject true, {acc,item -> acc && item.validate()}
}
the three arguement version of validate expects you to add errors to the errorCollection. https://grails.github.io/grails2-doc/2.5.6/ref/Constraints/validator.html
Plus using a return statement inside of .each doesn't work like the above example. It just exits the closure and starts the next iteration. The validator from the other answer was just returning val (the result of val.each is just val)
You need to spin through the entire collection looking for non valid options.

GORM constraints: validator for boolean fields

I'm trying to set a simple restriction on the field of the domain object using the closure in constraints but it does not work.
For example, I have three fields:
boolean organization1 = false
boolean organization2 = false
boolean organization3 = false
organization3 field can be set only if organization1 field is set:
class Organization {
boolean organization1 = false
boolean organization2 = false
boolean organization3 = false
static constraints = {
organization1()
organization2()
organization3(validator:{organization3, organization -> return organization.organization1 ? true : false })
}
}
Controller actions and GSP- views I get by using scaffolding. That's what happens:
How to properly set a restriction? I would be very grateful for the information. Thanks to all.
Not sure if I got it correctly, but I'd put the validator this way:
static constraints = {
organization3 validator:{ org3, org -> !org3 || org3 && org.organization1 }
}

backbone.js model validation isValid() returns true for invalid attribute

I was trying to check the validity of individual attributes using isValid method. It is returning true for an invalid attribute. My code is as follows:
person = Backbone.Model.extend({
defaults:{
name:"default name",
age:0
},
initialize:function(){
this.on("invalid",function(model,errors){
console.log(JSON.stringify(errors));
});
},
validate:function(attrs){
errors=[];
if(attrs.age<0){
errors.push({attribName:"age",errorMsg:"age should be grater than 0"});
}
return errors.length>0?errors:false;
}
});
var person1 = new person();
person1.set({
age:-5
});
console.log("checking validity of model:"+person1.isValid());
console.log("checking for validity of age attribute:"+person1.isValid('age'));
isValid() works fine if used to check the validity of the model as a whole and returns false. But when I try to check the age attribute i.e isValid('age') it returns true when it should return false.
isValid() is an underscore.js function, right? Doesn't it support passing an attribute to check for its validity? What am I missing here?
Short version
Model.isValid doesn't accept an attribute name as argument and has to be used on the whole model. If you don't, you're on undocumented territory and you will get weird behaviors.
To check individual attributes, you will have to set up your own mechanism.
Long version, why you get a different value
Model.isValid does in fact accept an (undocumented) options hash as its first argument and it internally forwards this hash to Model._validate via
this._validate({}, _.extend(options || {}, { validate: true }))
trying to set a validate attribute to true. But at this point, options is a string and won't be modified by _.extend. _validate looks like
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;
// ...
}
checking if it indeed has to validate the model, options.validate is undefined and your isValid call gets back a true value.
isValid is a backbone API : http://backbonejs.org/#Model-isValid
The reason it is returning true is, the parameter accepted by isValid is an options paramter. It has to be an object.
One of the scenario you use options is :
validate: function(attrs, options) {
if(options.someSpecialCheck) {
// Perform some special checks here
} else {
// Perform some regular checks here
}
}
myModel.isValid({someSpecialCheck: true});

Resources