Baeuerle Associates, LLC
 5570 Leeward Ln
 Tilghman, MD 21671

Validation

Index

Usage of own validation method
Regular Expressions
Command Objects

Validating Domain Classes

Grails allows you to apply constraints to a domain class that can then be used to validate a domain class instance. Constraints are applied using a "constraints" closure which uses the Groovy builder syntax to configure constraints against each property name, for example:

class Contact {
   String firstName
   String middleInitial
   String lastName
   String phone
   String email
   Date birthDay
   Address address

   static constraints = {
       firstName(blank:false,size:3..30)
       middleInitial(blank:false, maxSize:1)
       lastName(blank:false,maxSize:30)
       phone(blank:false, unique:true, matches:/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/)
)
                
email(blank:false,email:true)
       birthday(nullable:false,min:new Date())
       address(nullable:false)
   }
}

To validate a domain class you can call the "validate()" method on any instance:

   def contact = new Contact()
   //populate properties e.g. contact.properties = params
   if ( contact.validate() ) {
       do work.....
   }
   else {
       contact.errors.allErrors.each {
           println it
       }
   }

In the reference that follows, className.propertyName.validationConstraint refers to the error message codes defined in /grails-app/i18n/message.properties_.

For example, referring to the above class, the error message might be defined as: contact.firstName.blank=Please enter a firstName
contact.firstName.size.toobigl=Firstname [{2}] exceeds the maximum size of [{3}]
contact.phone.matches.invalid=Phone No [{2}] invalid

[{0}] = property
[{1}] = class
[{2}] = value
[{3}] = constraint

For the See more Grails standard validations
Grails validation reference.


Usage of own validation method.  Back

For each property validation, you can write your own validation method.
To call your own method is validator: with a closure (param1 and/or param2)
param1 = property (zipCode)
param2 = object instance address

class Address {

   String zipCode

   static constraints = {
       zipCode(nullable:false, validator: { val, obj ->
           if ( !obj.validateZipCode(val) ) return ['invalid']
       })
   }

   def boolean validateZipCode(def zipCode){
       def zipCode = ZipCode.get(zipCode)
       if ( zipCode )
           return true
       else
           return false
     }
}


 

[Home] [Company] [Services] [Grails] [Grails beyond CRUD] [Domain] [Controller] [View] [Validation] [Links]

For additional questions please eMail to Baeuerle Associates, LLC
©Copyright 2003 Baeuerle Associates, LLC. All rights reserved.