Grails with Java: Learning the Basics of Grails Domain Constraints

Grails Constraints

Grails is a framework developed in Groovy, which internally utilizes Java to rapidly build applications. I recently had the opportunity to work on a Grails application, prompting me to share insights about Grails constraints.

In any web programming language, form-level validations are essential. These validations can occur either at the client level or server level. Client-level validations involve checking data on the browser before sending it to the server. This can be accomplished using scripting languages like JavaScript or VBScript. On the other hand, server-level validations send the entered data to the server, where it undergoes various validations defined at the domain level. For domain-level validations, we can use Java or .NET languages. Groovy, the language of Grails, leverages Java for domain-level validations.

Grails allows the definition of domain-level constraints in the following manner:

Grails can be defined as the constraints validation on domain class in the following way

class Employee {
    String eid
    String name
    String email
    Integer sal

    static constraints = {
        eid(unique: true)
        name(blank: true)
        email(email: true)
    }
}

In the Employee domain class, validation constraints are expressed in Groovy on Grails. These constraints are defined within a block containing all the required validation configurations for the domain class.

The following are examples of domain-level constraints available in Groovy and Grails.

  • blank: Specifies whether the member variable in the domain can be null or not. Usage: name(blank: true/false).
  • creditCard: Checks if the member variable is a credit card.
  • email: Validates whether the email adheres to correct email validation rules.
  • inList: Ensures that the member variable’s value is within a specified list.
  • matches: Compares the value with a regular expression.
  • max: Verifies that the value does not exceed the allowed maximum.
  • maxSize: Specifies the maximum size of the variable.
  • min: Sets the minimum allowed value.
  • minSize: Defines the minimum value allowed.
  • notEqual: Checks whether the value is not equal to the specified value.
  • nullable: Specifies whether the member value is nullable or not.
  • range: Specifies a range of valid values.
  • unique: Ensures that the variable’s value is unique.

These validators are predefined and come with the Grails plugin framework. Additionally, Grails allows the definition of custom validators for specific requirements, extending the flexibility of server-side validations.