Spring MVC Form Validation Example - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Here I am going show a simple Spring MVC Form Validation Example.
Technologies :
Spring Framework 3.1.1.RELEASE
Hibernate Validator 4.2.0.Final
Jstl 1.2
Java 8
Here we are going to validate registration form with different fields like firstName, lastName, age, email by using simple spring validation framework.
Project Structure :
 
Dependencies: pom.xml
<dependencies>
  <!-- Spring -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework-version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework-version}</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.2.0.Final</version>
  </dependency>

  <!-- Servlet -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.1</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
</dependencies>
RegistrationBean.java
package com.spring.controller;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public class RegistrationBean {

  @NotNull
  @Size(min = 1, message = "You can't leave this empty.")
  private String firstName;

  @NotNull
  @Size(min = 1, message = "You can't leave this empty.")
  private String lastName;

  @NotNull(message = "You can't leave this empty.")
  @Min(value = 13, message = "You must be greater than or equal to 13")
  @Max(value = 19, message = "You must be less than or equal to 19")
  private Integer age;

  @Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$", message = "Invalid email")
  private String email;

  public String getFirstName() {
    return firstName;
  }

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

  public String getLastName() {
    return lastName;
  }

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

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

}
@NotNull: It won’t allow the null values.
@Min(13): Won’t allow if the age is a min of 13
@Max(19): Won’t allow if the age is a max of 19
@Pattern: Applied given regex pattern on the specified field (our case it is email)
Registration Form : register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Spring MVC Form Validation</title>
      <style>
         .error {
         color: red
         }
      </style>
   </head>
   <body>
      <form:form action="processForm" modelAttribute="registration">
         <div align="center">
            <h2>Register Here</h2>
            <table>
               <tr>
                  <td>First name</td>
                  <td>
                     <form:input type="text" path="firstName" />
                  </td>
                  <td>
                     <form:errors path="firstName" cssClass="error" />
                  </td>
               </tr>
               <tr>
                  <td>Last name (*)</td>
                  <td>
                     <form:input type="text" path="lastName" />
                  </td>
                  <td>
                     <form:errors path="lastName" cssClass="error" />
                  </td>
               </tr>
               <tr>
                  <td>Age </td>
                  <td>
                     <form:input type="text" path="age" />
                  </td>
                  <td>
                     <form:errors path="age" cssClass="error" />
                  </td>
               </tr>
               <tr>
                  <td>Email </td>
                  <td>
                     <form:input type="text" path="email" />
                  </td>
                  <td>
                     <form:errors path="email" cssClass="error" />
                  </td>
               </tr>
               <tr>
                  <td></td>
                  <td><input type="submit" value="Submit" /></td>
               </tr>
            </table>
         </div>
      </form:form>
   </body>
</html>

Registration Controller: RegistrationController.java
package com.spring.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RegistrationController {

  @RequestMapping(value = "/register", method = RequestMethod.GET)
  public String showForm(Model model) {
    model.addAttribute("registration", new RegistrationBean());
    return "register";
  }

  @RequestMapping(value = "/processForm", method = RequestMethod.POST)
  public String processForm(@Valid @ModelAttribute("registration") RegistrationBean register,
      BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
      return "register";
    } else {
      return "success";
    }

  }
}
properties file :
typeMismatch.registration.age=Invalid Number
Success page: success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <title>Registration Confirmation</title>
   </head>
   <body>
      Hello <font color="green">${registration.firstName} ${registration.lastName} </font> you have successfully registered with us.
   </body>
</html>
Run the application :
http://localhost:8080/Spring-MVC-Form-Validation/register
Invalid Form Fields :
Leaving all form fields empty.
Invalid Age :
Using @Max and @Min validations on age attribute.
Invalid Age Format :
Giving invalid age (Not a number) validation
Success Form :
Success Page :
Happy Learning 🙂


Spring-MVC-Form-Validation

File size: 29 KB
Downloads: 997


Spring Form Custom Validation Example
Spring Boot Validation Login Form Example
Spring Web MVC Framework Flow
Spring MVC Tiles Example (Apache Tiles)
Spring Boot Security MySQL Database Integration Example
Python Selenium Automate the Login Form
@Qualifier annotation example in Spring
PHP Form Handling Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Java Configuration Example
Simple Spring Boot Example
BeanFactory Example in Spring
Spring Collection Map Dependency Example
Spring Bean Autowire By Constructor Example
Spring MVC Login Form Example Tutorials

Spring Form Custom Validation Example
Spring Boot Validation Login Form Example
Spring Web MVC Framework Flow
Spring MVC Tiles Example (Apache Tiles)
Spring Boot Security MySQL Database Integration Example
Python Selenium Automate the Login Form
@Qualifier annotation example in Spring
PHP Form Handling Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Java Configuration Example
Simple Spring Boot Example
BeanFactory Example in Spring
Spring Collection Map Dependency Example
Spring Bean Autowire By Constructor Example
Spring MVC Login Form Example Tutorials






Ravinath
March 16, 2019 at 12:49 pm - Reply 

Can I have use register.jsp to register.html? If yes! Please suggest to me.









Ravi
March 16, 2019 at 6:14 pm - Reply 

Can I create register.html  instead of register.jsp file? Please Suggest me. If Yes! please give me an example.










Ravinath
March 16, 2019 at 12:49 pm - Reply 

Can I have use register.jsp to register.html? If yes! Please suggest to me.




Can I have use register.jsp to register.html? If yes! Please suggest to me.





Ravi
March 16, 2019 at 6:14 pm - Reply 

Can I create register.html  instead of register.jsp file? Please Suggest me. If Yes! please give me an example.




Can I create register.html  instead of register.jsp file? Please Suggest me. If Yes! please give me an example.