API / Apache Grails Interview questions
How do you enforce validation constraints on a Grails domain class?
Validation rules are declared in a domain class's static constraints closure, mapping each property to one or more constraint keywords, which GORM then automatically checks every time save() or validate() is called on an instance.
| Constraint | What it enforces |
| blank(false) | Property cannot be an empty string |
| nullable(false) | Property must have a value (default for most types) |
| size(3..50) | String/collection length falls within a range |
| email(true) | Value must be formatted as a valid email address |
| unique(true) | Value must not already exist elsewhere in that column |
Constraints can also be combined and made conditional, chaining multiple rules onto a single property, and a custom validator closure can express logic that doesn't fit any of the built-in constraint keywords, giving arbitrary validation logic access to both the property's own value and the rest of the object being validated. Because these constraints live directly on the domain class, they're enforced consistently no matter where in the application a save actually happens — a controller, a service, a background job — rather than needing to be re-checked manually at every call site.
More Related questions...