Form Data Validations

Spring has provided inbuilt validations framework. Since we are using Spring framework validation implementation, we will have to use Spring Form tags to get the errors and set the form bean and variable names. These are very simple need not to study separately.

Validations will be applied by using annotations to fields of pojo class. As a developer we need not to write logic for everything basic validations they already provided so it’s easy to use. Spring has not stopped us from writing our own validations we will see how to implement our own validations.

Firstly we need to have jars in our project to get it implemented. Your pom.xml should have following dependencies added. Spring used javax-validation and hibernate-api to achieve this.

pom.xml


Then add validation rules to User.java, I have added for String name in user class.

It provides a set of validation annotations we can use to validate the data, such as @NotNull, @Max, @Min, @Size, @Pattern, @Future & @Past.

User.java


Some more examples are:

The password is required, can’t be empty, min length of 8, and must contain at least one digit, one lower char and one upper char, one special char, and doesn’t contain spaces.


One common question here, “What’s the difference between @NotNull, @NotEmpty, and @NotBlank ?

  • @NotNull: Checks if the value is not null, disregarding the content (it can be empty). Used with dates, collections, map, array, etc.

  • @NotEmpty: Checks if the value is not null nor empty, allowing empty spaces but size has to be greater than zero. Used with strings, collections, map, array etc.

  • @NotBlank: Checks if the value is not null nor empty, and the trimmed length is greater than zero. Used with strings.

Now you need to change as below.

userForm.jsp


We’ll use springform:errors tag to display the validation error messages (if exist). In addition we can apply a CSS class for displaying errors.

In Controller add below code.

UserController.java


In above code the @Valid annotation performs validation rules on user object (we defined earlier in User class). The results of the validation will be placed in the BindingResult object.

Now run a project. You will see messages are appearing.

spring mvc form data handling project structure

Now how to bring these errors from properties file. This is good for internationalization.

Add file ValidationMessages.properties – keep same name in src/main/resources

Add below lines there.

ValidationMessages.properties


In Users.java change validation like this.

Now run a project. You will see messages are appearing from properties file.