Thursday, September 2, 2010

Grails partial validation

So yesterday I pointed out how partial binding could be done with your domain classes. Today, I will point out how partial validation of your domain classes can be achieved. Let's change our domain class from yesterday to have some constraints.

package com.xyzcorp

class Widget {
Date dateCreated
String sku
int quantity

static constraints = {
dateCreated(nullable: false)
sku(nullable: false, blank: false, maxSize: 15)
quantity(nullable: false, min: 0)
}

static mapping = {
autoTimestamp true
}
}

Even though the nullable constraints are true by default for all properties on a domain class, I find it helpful to actually include them so there is no confusion about the intent. Given the same situation as yesterday where we only want to bind the sku property we will only validate the sku property with partial validation. Here is an example of how that is accomplished:

// some code within our controller or service
// instead of calling widgetInstance.validate() we can do the following
widgetInstance.validate(['sku'])

What we are doing here is passing a map of properties to validate telling it specifically which properties to validate. As you can see this isn't a difficult thing to do, it's just one of those things that you may not have known about.

Using partial validation in combination with partial binding Grails gives you the tools to avoid being forced to use command objects. Another use of partial validation is to avoid expensive validation of properties that you know haven't changed. Also, this is also very useful when you need to test the validation implementation for a specific property in a unit/integration test.

Questions? Comments? Suggestions? Let me know!

2 comments:

  1. So does the partial validation performed allow saving the object without doing the full validation, or would you need to specify validate: false as a save option? If not, is there a way to perform the save with the same partial validation?

    ReplyDelete
  2. Very good question. As far as I can tell, save only allows for you to enable (default) or disable (using validate: false) but not partial at the time of save().

    However, I haven't gone through the source to verify this, so I could be wrong.

    ReplyDelete