Hello! This is the 4th series to play with Java from scratch. I just named it.
Click here for articles up to the last time ↓
This time, I would like to add validation to the echo application I made last time.
Currently, character strings, numbers, and environment-dependent characters can be entered in any number of characters, so if you send a phantom document, the display will be corrupted as shown below.
scared. If Hatena is lined up in the name, it will create a disturbing atmosphere. Is it garbled? I don't like the fact that Zero has broken through the screen width.
So, this time, I'm going to validate with the following requirements, like the user name of some service. In case of an error It is an image that an error message is displayed on the same screen.
--Available character types: Half-width alphanumeric characters only --Character limit: 4 characters or more
The finished product has the following shape. (The background color has been changed to a color that is easy on the eyes)
The following annotations have been added to the form class.
--@NotBlank
: You can check that it is not null or empty string [^ 1]
--@Size
: You can specify the minimum and maximum values using the attribute min or max.
--@Pattern
: You can specify a regular expression pattern string with the attribute value regexp. This time I used a regular expression that allows only half-width alphanumeric characters
[^ 1]: Use @NotNull to check only null
EchoForm.java
package com.example.form;
import java.io.Serializable;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotBlank;
public class EchoForm implements Serializable {
private static final long serialVersionUID = 1L;
@NotBlank
@Size(min = 4)
@Pattern(regexp = "[a-zA-Z0-9]*") //Must be alphanumeric
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Write only the modified echo method. There are two changes below.
--Added BindingResult class to argument
. BindingResult contains the input check result. Execution of input check and generation of BindingResult are the parts that the framework is responsible for, so there is no need to implement it. (From Introduction to Spring)
--Added branch on error
.
If an error occurs in the check by annotation, I do not want you to go to the "Hello $ {username}" screen, so I am changing to return the same page.
EchoController.java
@RequestMapping(value = "echo", method = RequestMethod.POST)
public String echo(@Validated EchoForm echoForm, BindingResult result, Model model) {
if (result.hasErrors() ) {
model.addAttribute("name", echoForm.getName());
return "index";
}
model.addAttribute("name", echoForm.getName());
return "echo";
}
I want to display the error message in red as shown below only when an error occurs ... This can be done with Spring!
Since we have already bound the form object last time, we can get the error information of echoForm and insert it into Thymeleaf to create HTML. Spring is amazing. Thymeleaf is amazing.
Only the form part is described.
In the place surrounded by span, the error message is displayed only when the object is in error [^ 2]. Specifically, because the form object's properties are set in the th: errors attribute, only error messages for the specified properties are displayed.
If there are multiple error messages, <br />
will be automatically entered. Thank you.
[^ 2]: I referred to the implementation of this page.
index.html
<form th:object="${echoForm}" th:action="@{/echo}" method="POST">
<div>Please enter your username</div>
<div>(4 or more half-width alphanumeric characters)</div>
<div>
<input type="text" th:field="*{name}" />
<button>I will send</button>
</div>
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" style="color: red"></span>
</form>
Actually, if you execute with the implementation so far, the error message will be the default message (English) of the annotation, so the error will be as follows.
I don't like this a little ... The above may still be passed with a fashionable error message ❤️, but the size number is unclear to the user ... Let's fix this to a Japanese error message!
It seems desirable to define Bean Validation error messages by Spring MVC in the properties file. There seem to be several methods, but I chose that because it was easy to understand how to create ValidationMessages.properties directly under the classpath.
Create a new ValidationMessages.properties under resources.
The content is a simple implementation that just rewrites the message of the annotation used.
ValidationMessages.properties
org.hibernate.validator.constraints.NotBlank.message=Input is required.
javax.validation.constraints.Size.message=Must be at least 4 characters.
javax.validation.constraints.Pattern.message=Only half-width alphanumeric characters are valid.
By the way, when I just pasted the above into ValidationMessages.properties, it automatically became as follows just by inputting Japanese and pressing enter ... Because the standard Bean of Spring Boot is not UTF-8 Multibyte It seems that the characters are garbled.
ValidationMessages.properties
org.hibernate.validator.constraints.NotBlank.message=\u5165\u529B\u5FC5\u9808\u3067\u3059\u3002
javax.validation.constraints.Size.message=4\u6587\u5B57\u4EE5\u4E0A\u3067\u306A\u304F\u3066\u306F\u3044\u3051\u307E\u305B\u3093\u3002
javax.validation.constraints.Pattern.message=\u534A\u89D2\u82F1\u6570\u306E\u307F\u6709\u52B9\u3067\u3059\u3002
As mentioned in the comment section of Qiita here, probably because I am also a Spring 2 system and Java 11 or higher, UTF in the file properties If I set it to -8, the application worked fine. Just right click on the file> Properties> Resource and change the Text file encoding from default to UTF-8.
Now when I try to save the file I get the following warning, but it worked fine with Save as UTF-8
.
The message is now in Japanese as shown below!
This time, I had a little trouble with the Thymeleaf notation of the text addition part at the time of error and the Japanese localization of ValidationMessages.properties! The method introduced this time is suspicious if it is Spring 1 system, so please check it as appropriate.
Thank you for reading!
Recommended Posts