Validate form entries with Spring Boot

 

Getting started in Spring Boot, Part 7 Validating Form Entries with Spring Boot

After having taken a look at the architecture of Spring-boot applications in the last post of the series, it is now time to check user input for syntactic correctness.

Company about the topic

Entries on a website should be validated and reported, Spring Boot provides a validation starter for this.Entries on a website should be validated and reported, Spring Boot provides a validation starter for this.

The easiest way to validate form entries in Spring Boot is to use the Bean Validation Framework, which has existed since 2017 in the form of Bean Validation 2.0. The integration of the framework takes place by adding the following starter dependency in the POM:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Under the hood, the Hibernate validator, the reference implementation of the Validation API, is used for this purpose. In the Spring Tool Suite (STS) alternatively, the module can be integrated directly via a context menu: Right-click on pom.XML and then Spring & gt; Add Starters and the dependency Validation inflict. The validation framework is therefore ready for use.

As an example object we take the person known from the previous contributions, which is now extended by an e-mail address. The playback of the corresponding set and get methods is omitted here for space reasons, you can easily use them in STS via Source & gt; Generate Getters and Setters… let generate:

public class Person {   private String firstname;
private String lastname;
private String email;
// ...
}

The validation of the person properties is done by annotating the corresponding properties. For example, to ensure that first and last names are filled, the annotation is used for these properties @NotBlank used. A valid e-mail can be sent by @Email force:

public class Person {   @NotBlank
private String firstname;
   @NotBlank
private String lastname;
   @Email
private String email;
   // ...
}

The Thymeleaf view for submitting the form is also already known from a previous post, it is also extended by the e-mail address:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
   <h1>Benutzerdaten eingeben:</h1>
<form action="https://www.dev-insider.de/formulareingaben-validieren-mit-spring-boot-a-996378/#" th:action="@{/}" th:object="${person}" method="post">
<p>
Vorname: <input type="text" th:field="*{firstname}" />
</p>
<p>
Nachname: <input type="text" th:field="*{lastname}" />
</p>
<p>
Email: <input type="text" th:field="*{email}" />
</p>
<p>
<input type="submit" value="Submit" /> <input type="reset"
value="Reset" />
</p>
</form>
</body>
</html>

In the controller method that receives the post request, the annotation is @Valid before the person object in the argument list new. The Annotation is needed to activate the validation mechanism :

@Controller
public class PersonController {
   @GetMapping("https://www.dev-insider.de/")
public String home(Model model) {
Person person = new Person();
model.addAttribute(person);
return "home";
}
   @PostMapping("https://www.dev-insider.de/")
public String home(@Valid Person person, Model model) {
model.addAttribute(person);
return "home";
}
}

If you now try to send the form with an empty first or last name or a completed but invalid e – mail address, an error is displayed in the console and an error page with stacktrace is displayed. An example of such a console message is reproduced here:

Field error in object 'person' on field 'firstname': rejected value []; codes [NotBlank.person.firstname,NotBlank.firstname,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [person.firstname,firstname]; arguments []; default message [firstname]]; default message [darf nicht leer sein]

The content of the message indicates that the validation has worked. Only the visualization of the result leaves much to be desired. The user should probably be alerted to the incorrect input by a note on the page with the form; not by a stacktrace that is difficult to read.

The error page with the stracktrace is created by adding the interface BindingResult go to the argument list of the post method. The object can be queried for possible errors. Here in the example, the errors are only output and then routed back to the form, but with error-free validation it could also be forwarded to a success page by means of Redirect:

@PostMapping("https://www.dev-insider.de/")
public String home(@Valid Person person, BindingResult bindingResult, Model model) {
   if (bindingResult.hasErrors()) {
bindingResult.getAllErrors().stream().forEach(System.out::println);
}
model.addAttribute(person);
return "home";
}

The validation errors that have occurred are passed to the HTML form and can be displayed there:

<p th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}"/>

The text of the message (“must not be empty”) can be used in the validation annotation with the help of the attribute message be adjusted :

public class Person {   @NotBlank(message = "Vorname muss angegeben werden")
private String firstname;
}

Incorrect entries in the form are found.Incorrect entries in the form are found.

(Photo: Dr. Koller)

As the Screenshot shows, the result is quite useful. In practice, the affected text fields and error messages might still be colored red using CSS.

In addition to the annotations presented above, there are several other annotations that can be used, for example, to check certain number thresholds or the value of a boolean variable:

Details on the exact use of annotations can be found in the Hibernate Validator documentation.

(ID:47107076)

Ready to see us in action:

More To Explore

IWanta.tech
Logo
Enable registration in settings - general
Have any project in mind?

Contact us:

small_c_popup.png