Spring Form Validation

 The Need for validation is to check the user input form for 

  • require fields
  • Validate numbers in a range
  • validate format (Postal code)
  • custom business rule

Java standard bean Validation API
  • Java has a standerd Bean validaton API
  • Defines  metadata model and API for entity validation 
  • Not tied to either the web tier or the persistence tier
  • Available for server-side apps and also client-side javaFx/Swigns apps.
  • Spring version 4 and higher supports Bean Validation API
  • The preferred method for validation when building the spring app. that means only adding annotations provided by validation API.
  • Simply add validation JAR to our Project.
Bean Validation Features:
  • Required - to check filed is required 
  • validate length - to check the length of the input
  • Validate numbers - 
  • Validate with regular expression
  • custom validation

Validation Annotation:

  • @NotNull - Checks that the annotation value is not null.
  • @Min - Must be a number >= value
  • @Max - Must be a number <= value
  • @Size - Size must match the given size
  • @Pattern - Must match a regular expression pattern,
  • @Future /@Past - The date must be in the future or past of given
there are so many other annotations

Tricky things with version numbers
Tow release of Hibernate validator 
  • Hibernate Validator 7 is for Jakarta EE 9 project.
  • Hibernate Validator 6.2 is compatible with spring 5.
Hibernate Validator 6.2 has the Same features as HIbernet Validator 7

Setup Hibernate validator in our project

Go to the https://hibernate.org/validator/releases/6.2/




Download the JAR Files

It will start the downloading 


Extract the Zip file and add all Jars files in your project libs.




Development Process : 

Add Validation Rule to customer class

public class Customer {
private String firstName;

@NotNull(message = "is required")
@Size(min=1)
private String lastName;

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}


}

Display the error message on the HTML form
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Customer Register Form</title>

<style>
.error {color:red}
</style>
</head>
<body>
<form:form action="processForm" modelAttribute="customer">
First Name : <form:input path="firstName" />
<br><br>

Last Name (*) : <form:input path="lastName" />
<form:errors path="lastName" cssClass="error"/>

<input type="submit" value="submit" />
</form:form>
</body>
</html>

Perform validation in the controller class
@Controller
@RequestMapping("/customer")
public class CustomerController {

@RequestMapping("/showForm")
public String showForm(Model theModel) {
theModel.addAttribute("customer",new Customer());
return "customer-form";
}

Create show form jsp file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Spring Boot MVC - Home page</h2>

<hr>

<a href="showform">Hello word form</a>
<br><hr>
<a href="customer/showForm">Customer form</a>
</body>
</html>

Add process 

@Controller
@RequestMapping("/customer")
public class CustomerController {

@RequestMapping("/showForm")
public String showForm(Model theModel) {
theModel.addAttribute("customer",new Customer());
return "customer-form";
}

@RequestMapping("/processForm")
public String processForm(@Valid @ModelAttribute("customer") Customer theCustomer,
BindingResult theBindingResult) {

if(theBindingResult.hasErrors()) {
return "customer-form";
}else {
return "customer-confirmaton";
}

}
}
Customer confiramtion 


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>Customer confirmation</head>
<body>
the customer is conformed : ${customer.firstName} ${customer.lastName} }
</body>
</html>

Output : 
















Comments

Popular posts from this blog

Primitive Data Types in java

let - Keyword in JavaScript (Block scope)

Coding Problem 4: Smallest window containing 0, 1 and 2 [GFG - Problem Solving]