Grails: can I make the validator applicable only for creation (do not update / edit)

I have a domain class that must have a date after the day of creation in one of its fields.

class myClass { Date startDate String iAmGonnaChangeThisInSeveralDays static constraints = { iAmGonnaChangeThisInSeveralDays(nullable:true) startDate(validator:{ def now = new Date() def roundedDay = DateUtils.round(now, Calendar.DATE) def checkAgainst if(roundedDay>now){ Calendar cal = Calendar.getInstance(); cal.setTime(roundedDay); cal.add(Calendar.DAY_OF_YEAR, -1); // <-- checkAgainst = cal.getTime(); } else checkAgainst = roundedDay return (it >= checkAgainst) }) } } 

So, a few days later, when I change only the line and the call, the save fails because the validator is double-checking the date, and now it is in the past. Can I make sure that the validator only starts when it is created, or somehow I can change it to determine if we are creating or editing / updating?

@Rob H I'm not quite sure how to use your answer. I have the following code causing this error:

 myInstance.iAmGonnaChangeThisInSeveralDays = "nachos" myInstance.save() if(myInstance.hasErrors()){ println "This keeps happening because of the stupid date problem" } 
+6
source share
2 answers

You can check if the id parameter is set as an indicator of whether it is a new mutable instance or an existing persistent instance:

 startDate(validator:{ date, obj -> if (obj.id) { // don't check existing instances return } def now = new Date() ... } 
+12
source

One option might be to specify which properties you want to check. From the doc:

The verification method accepts an optional argument to the list, which may contain property names that must be confirmed. When the list is transferred only to the property verification method, the ones defined in the list will be confirmed.

Example:

 // when saving for the first time: myInstance.startDate = new Date() if(myInstance.validate() && myInstance.save()) { ... } // when updating later myInstance.iAmGonnaChangeThisInSeveralDays = 'New Value' myInstance.validate(['iAmGonnaChangeThisInSeveralDays']) if(myInstance.hasErrors() || !myInstance.save(validate: false)) { // handle errors } else { // handle success } 

This seems a bit hacky as you bypass some Grails built-in kindness. You want to be careful that you do not bypass any necessary verification in the domain, which usually happens if you just call save() . I would be interested to see the solutions of others, if there are more elegant ones.

Note. I really do not recommend using save(validate: false) if you can avoid this. This will inevitably lead to unforeseen negative consequences in the future, if you are not very careful in how you use it. If you can find an alternative, be sure to use it.

0
source

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


All Articles