Table of contents
1.
Introduction
2.
Validation
3.
Declaring Constraints
4.
Validating Constraints
4.1.
Validation Basics
4.2.
Validation Phases
5.
Sharing Constraints Between Classes
5.1.
Global Constraints
5.2.
Importing Constraints
6.
Validation on the Client
6.1.
Displaying Errors
6.2.
Highlighting Errors
6.3.
Retrieving Input Values
7.
Frequently Asked Questions
7.1.
Which is better, grails or Spring?
7.2.
Is Grails a spring boot?
7.3.
Is Django better than Spring?
7.4.
Is Flask better than Spring?
7.5.
Do grails use Maven?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Grails-Validation

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

REST is more of an architectural pattern than technology in and of itself. Uses raw XML or JSON as a means of communication; Along with HTTP methods like GET, PUT, POST, and DELETEREST is required to have URL patterns that are "representational" of the underlying system.

An action type corresponds to each HTTP method. For instance, GET is used to retrieve data; POST is used to create data, PUT is used to update, etc.

RESTful API creation is made simple by the versatile features of Grails. As the Article shows, creating a RESTful resource requires only one line of code.

Grails CN

Validation

The Data Binding and Validator API from Spring is the foundation for Grails' validation functionality. With its constraints mechanism, Grails offers a standardized method to establish validation "constraints."

Declarative validation requirements can be expressed using GRAIL and constraints. In addition to domain classes, URL Mappings and Command Objects also support rules.

Declaring Constraints

Due to constraints, the property is attached to a code block, and restrictions are specified within a domain class:

class User {
   String new_login
   String new_password
   String new_email
   Integer new_age


   static new_constraints = {
     ...
   }
}

 

Then, to express constraints, you utilize method calls that correspond to the named arguments for the property to which the rule applies:

class User {
   ...


   static new_constraints = {
       new_login size: 5..15, blank: false, unique: true
       new_password size: 5..15, blank: false
       new_email email: true, blank: false
       new_age min: 18
   }
}

 

In this example, we've said that the login attribute must be unique, have a length of between 5 and 15, and not be blankAge, email, and password attributes have also been restricted.

A constraint depends on a value, such as an instance of java.util.Date. You may have to consider that conditions are only ever evaluated once.

class User {
   ...


   static new_constraints = {
       // When constraints are assessed, this Date object is produced, not
       // whenever a User class instance is validated.
       birthDate max: new Date()
   }
}

Validating Constraints

Validation

Validation Basics

If you want to verify a domain class instance, call this validation method:

def new_user = new User(params)


if (new_user.validate()) {
   // do something with the User
}
else {
   new_user.errors.allErrors.each {
       println it
   }
}

 

The domain class error attribute is an instance of the Spring Errors interface. The Errors interface allows searching through validation errors and getting the original data.

Validation Phases

In Grails, validation occurs in two stages. The first stage is data binding, which takes place when you bind request parameters to an instance using methods like:

def new_user = new User(params)

 

You may already have errors in the error property due to type conversion (such as converting Strings to Dates). Using the Errors API, you may verify these and get the original input value:

if (new_user.hasErrors()) {
   if (new_user.errors.hasFieldErrors("new_login")) {
       println new_user.errors.getFieldError("new_login").rejectedValue
   }
}

 

When you use the validate or save command, validation enters its second step. At this point, Grails will check the bound values against the defined constraints. For instance, validate the same method by default calls before it runs, enabling you to write code like:

if (new_user.save()) {
   return new_user
}
else {
   new_user.errors.allErrors.each {
       println it
   }
}

Sharing Constraints Between Classes

Sharing Contstraints

Using Command Objects to validate user-submitted input and subsequently copying the properties of the command object to the appropriate domain classes is a frequent practice in Grails. This frequently indicates that the characteristics and constraints of your domain classes and command objects are shared. The rules might be manually copied and pasted between the two, but that method is prone to error. Use Grails' import mechanism and global constraints instead.

Global Constraints

You can specify restrictions in grail-app/conf/runtime.groovy in addition to domain classes, command objects, and other validatable classes:

grails.gorm.default.new_constraints = {
   '*'(nullable: true, size: 1..20)
   myShared(nullable: false, blank: false)
}

 

Although these restrictions are not exclusive to any one class, they can be referred to from any legal type:

class User {
   ...


   static new_constraints = {
       new_login shared: "myShared"
   }
}

 

Take note of the shared argument's usage, whose value is the name of a grails-defined constraint, gorm.default.constraints. Despite the configuration setting's name, these shared restrictions are accessible from any validatable class, including command objects.

The '*' constraint is an exception; it specifies that all properties in all acceptable classes will be subject to the related conditions (nullable and size in the example above). The constraints declared in a validatable class have the ability to override these defaults.

Importing Constraints

A different method of sharing constraints was added in Grails 2 that lets you import a collection of rules from one class into another.

Say you have a domain class that looks like this:

class User {
   String first_Name
   String last_Name
   String password_Hash


   static new_constraints = {
       first_Name blank: false, nullable: false
       last_Name blank: false, nullable: false
       password_Hash blank: false, nullable: false
   }
}

 

The next step is to create a command object called UserCommand that shares some of the restrictions and characteristics of the domain class. The importFrom() method is used to accomplish this:

class UserCommand {
   String first_Name
   String last_Name
   String new_password
   String new_confirmPassword


   static new_constraints = {
       importFrom User


       new_password blank: false, nullable: false
       new_confirmPassword blank: false, nullable: false
   }
}
Good Resources Representation

By doing this, all restrictions from the User domain class will be imported and applied to UserCommand. The import will disregard any limits in the source class (User) that don't match up with the properties in the importing class (UserCommand). Because those are the only attributes shared by the two types, only the 'first_Name' and 'lastName' constraints from the previous example will be imported into UserCommand.

Using the included and excluded parameters, you can control which constraints are imported. They both take a list of simple or regular expression strings as input to compare with the source constraints' properties. For instance, you would use: if you only wanted to import the "last_Name" constraint.

...
static new_constraints = {
   importFrom User, include: ["last_Name"]
   ...
}

 

Similarly, if you only wanted constraints with the word "Name" at the end:

...
static constraints = {
   importFrom User, include: [/.*Name/]
   ...
}

 

Excluding, naturally, does the opposite, specifying which constraints should not be imported.

Validation on the Client

Validation

Displaying Errors

Usually, you are redirected back to the view for rendering if you encounter a validation issue. Once you're there, you'll need a mechanism to show errors. Grails support a wide variety of tags for handling errors. Use render errors to render the errors as a list.

<g:renderErrors bean="${user}" />
Use each error and hasErrors if you need additional control:
<g:hasErrors bean="${user}">
 <ul>
  <g:eachError var="err" bean="${user}">
      <li>${err}</li>
  </g:eachError>
 </ul>
</g:hasErrors>

Highlighting Errors

Should a field be entered incorrectly, marking it with a red box or another indicator is frequently helpful. By calling the hasErrors method, this is also possible with that function. For instance:

<div class='value ${hasErrors(bean:user,field:'login','errors')}'>
 <input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>
</div>

 

This code examines the user bean's login field for errors and, if it finds any, adds an error CSS class to the div so that you can use CSS rules to emphasise the div.

Retrieving Input Values

Every error in Spring is a different instance of the FieldError class, which includes the original input value. This is advantageous because you can recover the user-inputted value by utilizing the error object and the field value tag:

<input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>

 

Whether a FieldError already exists in the User bean, this code will examine it to see if it can retrieve the login field's initial value.

Frequently Asked Questions

Which is better, grails or Spring?

Reviewers found Grails to be generally easier to use, set up, and conduct business with when comparing the two options. Reviewers, however, preferred Spring Framework's simplicity of management. Reviewers believe that Spring Framework and Grails better fit their business needs.

Is Grails a spring boot?

The Grails framework utilizes Spring Boot's time-saving capabilities, such as spring-powered dependency injection, as it is built on top of it.

Is Django better than Spring?

The "Frameworks (Full Stack)" category for the tech stack includes Django and Spring Boot. Because of Django's "fast development," "open-source," and "strong community," developers favour it. But because of its "powerful and practical," "simple setup," and "Java," Spring Boot is preferred.

Is Flask better than Spring?

Developers favor Flask because it is "lightweight," "Python," and "minimal," whereas Spring Boot is preferred because it is "powerful and handy," "Easy setup," and "Java."

Do grails use Maven?

The maven plugin will automatically execute the gradle wrapper inside the grails application.

Conclusion

So that's the end of the article. Grails-Validation

After reading about the Grails-Validation, Are you interested in reading/exploring more themes on Grails? Don't worry; Coding Ninjas has you covered.

However, if you want to give your work an edge over the competition, you might choose to enroll in one of our premium courses.

With our Coding Ninjas Studio Guided Path, you may learn about Data Structures & Algorithms, Competitive Programming, JavaScript, System Design, and more! If you want to put your coding skills to the test, check out the mock test series on Coding Ninjas Studio and participate in the contests! But if you've only recently started your schooling and are looking for answers to issues presented by digital titans like Amazon, Microsoft, Uber, and others. In this situation, you must consider the obstaclesinterview experiences, and interview package as part of your placement preparations. If you find our blogs valuable and fascinating, please vote them up!

Good luck with your studies!

Live masterclass