Form Validation – part 4 (using annotation @Pattern, @Past, @Max etc)

Using annotation @Pattern

Suppose we have a requirement where we want that user should be able to enter only alphabets in the field having input type=”text”

This can be achieved by adding @Pattern(regexp=”[^0-9]*”) annotation for the field for which we want to restrict the user.(Eg- studentName )

@Pattern(regexp=”[^0-9]*”)
private String studentName;

Next add the corresponding import to our Student class as below:

import javax.validation.constraints.Pattern;

validationMsg22

Now once we enter a Alpha-numeric or numeric character in the field in Student’s Name then Spring will validate ,if the field has any numeric character in the field and then bind the validation message in the controller class with the result variable and display it as an error on the RegistrationForm.jsp

validationMsg23

validationMsg3

Next we will see

Using @Past Annotation

Now similarly we want to put a validation for the Student Date-Of-Birth field so the the value enters should be a past date, we have to use @Past annotation in Student.java file

@Past
private Date studentDOB;

After this we will check our validation by putting a future date for Date-Of-Birth field.

past

Once we enter and submit the RegistrationForm,Spring application will throw the default validation message for @Past annotation as

past2

Similarly,

@Future : Checks whether the annotated date is in the future.
@Min : Check whether teh annotated value is higher than or equal to the specified minimum
@NotNull : Check that the annotated value is not null.
@NotEmpty: Check if the string is not null nor empty.

@NotEmpty is not supported by Bean Validation specification.Its only available to developers if they are using Hibernate Validator library in their Spring MVC Application


   

Comments are closed