Validation and Constraints

Site Admin · 11 Sep 2026 · 6 views

Why Validate?

Validation ensures that data meets your application's requirements before it reaches the database. In Grails, domain classes and command objects use constraints to define validation rules declaratively.

Defining Constraints

class Book {
    String title
    String isbn
    int pages

    static constraints = {
        title blank: false, size: 1..200
        isbn blank: false, unique: true, matches: /[0-9-]+/
        pages min: 1, max: 10000
    }
}

Common Constraints

  • blank: false - The value cannot be empty or blank.
  • nullable: false - The value cannot be null (default for most types).
  • unique: true - Ensures uniqueness in the database.
  • size: 1..200 - Restricts string or collection length.
  • min / max - Numeric range constraints.
  • matches - Regex pattern for string validation.
  • inList - Restricts to a list of allowed values.
  • email: true - Validates email format.

Custom Validators

For complex logic, use a custom validator closure:

static constraints = {
    isbn validator: { val, obj ->
        if (val && val.length() != 13) {
            return "isbn.length.invalid"
        }
    }
}

Checking Validation in Code

def book = new Book(title: "")
if (!book.validate()) {
    book.errors.allErrors.each { error ->
        println error.defaultMessage
    }
}

Key Points

  • Constraints are declared in the static constraints block.
  • GORM automatically runs validation before saving.
  • Built-in constraints cover most common validation needs.
  • Custom validators handle complex business rules.
  • The errors object provides detailed validation failure information.
Share this post:

Comments (0)

Please login or register to comment.