I tried to make the frame of the text box red when there was an input error, but I had a hard time implementing it, so I will post it.
OS: macOS Catalina 10.15.6 JDK:14.0.1 Spring Boot 2.3.3 jquery 3.3.1-1 bootstrap 4.2.1
In performing input check (validation), the author created a class as follows.
■ Controller class
SignupController.java
package com.example.demo.login.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.example.demo.login.domain.model.GroupOrder;
import com.example.demo.login.domain.model.SignupForm;
import com.example.demo.login.domain.model.User;
import com.example.demo.login.domain.service.UserService;
//Controller for new user registration
@Controller
public class SignupController {
@Autowired
private UserService userService;
//Transition to user registration screen
@PostMapping("/signup")
public String postSignUp(@ModelAttribute SignupForm form, Model model) {
return "signup/signup";
}
//Method for executing new user registration
@PostMapping("/signupUser") //Execute validation in the order set in "Group Order"
public String postSignUp(@ModelAttribute @Validated(GroupOrder.class) SignupForm form, BindingResult bindingResult, Model model) {
//An error occurred in the binding(Including validation error)If you do, the screen will change to the user registration screen.
if (bindingResult.hasErrors()) {
return postSignUp(form, model);
}
//Display newly registered contents on the console
System.out.println(form);
//Creating a User instance
User user = new User();
//Set the contents entered in the registration form in the User class
user.setUserId(form.getUserId());
user.setMailAddress(form.getMailAddress());
user.setPassword(form.getPassword());
//Throw a process to the service class with "User" that sets the form input contents as an argument
boolean result = userService.insertOne(user);
//Display the execution result of registration work on the console
if (result == true) {
System.out.println("insert successful");
} else {
System.out.println("insert failure");
}
//Transition to login screen
return "redirect:/login";
}
}
■ Validation group
GroupOrder.java
package com.example.demo.login.domain.model;
import javax.validation.GroupSequence;
//Execute validation in the order of "Valid Group 1" and "Valid Group 2" when registering a new user and updating user registration information.
@GroupSequence({ValidGroup1.class, ValidGroup2.class})
public interface GroupOrder {
}
ValidGroup1.java
package com.example.demo.login.domain.model;
//ValidGroup1 interface
public interface ValidGroup1 {
}
ValidGroup2.java
package com.example.demo.login.domain.model;
//ValidGroup2 interface
public interface ValidGroup2 {
}
■ Input form class
SignupForm.java
package com.example.demo.login.domain.model;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import lombok.Data;
//Signup Form used in new user registration form
@Data
public class SignupForm {
/*
*null Half-width space Error occurs when empty string(Classified as ValidGroup1)
*3 to 20 characters(Classified as Valid Group 2)
*/
@NotBlank(groups = ValidGroup1.class)
@Length(min = 3, max = 20, groups = ValidGroup2.class)
private String userId;
/*
*null Half-width space Error occurs when empty string(Classified as ValidGroup1)
*An error occurs if the email address is not in the format(Classified as Valid Group 2)
*/
@NotBlank(groups = ValidGroup1.class)
@Email(groups = ValidGroup2.class)
private String mailAddress;
/*
*null Half-width space Error occurs when empty string(Classified as ValidGroup1)
*3 to 20 characters(Classified as Valid Group 2)
*Alphanumeric only(Classified as Valid Group 2)
*/
@NotBlank(groups = ValidGroup1.class)
@Length(min = 3, max = 20, groups = ValidGroup2.class)
@Pattern(regexp = "^[a-zA-Z0-9]+$", groups = ValidGroup2.class)
private String password;
}
■ Error message
messages.properties
#Validation error message
signupForm.userId=User ID
NotBlank.signupForm.userId={0}Please enter
Length.signupForm.userId={0}Is{2}More than a letter{1}Please enter below the letter
signupForm.mailAddress=mail address
NotBlank.signupForm.mailAddress={0}Please enter
Email.signupForm.mailAddress=Please enter in email address format
signupForm.password=password
NotBlank.signupForm.password={0}Please enter
Length.signupForm.password={0}Is{2}More than a letter{1}Please enter below the letter
Pattern.signupForm.password={0}Please enter in half-width alphanumeric characters
searchForm.keyword=keyword
NotBlank.searchForm.keyword={0}Please enter
#Customize login error messages
AbstractUserDetailsAuthenticationProvider.badCredentials=The login ID or password is incorrect.
Initially, I created the html of the input form as shown below.
signup.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/template}">
<head>
<meta charset="UTF-8"></meta>
<title>SignUp</title>
</head>
<!--User registration screen-->
<body>
<div layout:fragment="content">
<div class="col-sm-4 offset-sm-4">
<div class="page-header">
<h1>User registration screen</h1>
</div>
<form method="post" th:action="@{/signupUser}" th:object="${signupForm}">
<table class="table table-bordered table-hover">
<tr>
<td> <!--If an error occurs in the "userId" field of the model object "signupForm", "has" in the class attribute-Add "error" and make the area around the textbox red
-->
<div class="form-group" th:classappend="${#fields.hasErrors('userId')}?'has-error'">
<input type="text" class="form-control" placeholder="Login ID" th:field="*{userId}"/>
<span class="text-danger"
th:if="${#fields.hasErrors('userId')}"
th:errors="*{userId}">
userId error
</span>
</div>
</td>
<tr>
<tr>
<td> <!--If an error occurs in the "mailAddress" field of the model object "signupForm", "has" in the class attribute-Add "error" and make the area around the textbox red
-->
<div class="form-group"
th:classappend="${#fields.hasErrors('mailAddress')}?'has-error'">
<input type="text" class="form-control" placeholder="mail address" th:field="*{mailAddress}"/>
<span class="text-danger"
th:if="${#fields.hasErrors('mailAddress')}"
th:errors="*{mailAddress}">
mailAddress error
</span>
</div>
</td>
<tr>
<tr>
<td> <!--If an error occurs in the "password" field of the model object "signupForm", "has" in the class attribute-Add "error" and make the area around the textbox red
-->
<div class="form-group"
th:classappend="${#fields.hasErrors('password')}?'has-errors'">
<input type="text" class="form-control" placeholder="password" th:field="*{password}"/>
<span class="text-danger"
th:if="${#fields.hasErrors('password')}"
th:errors="*{password}">
password error
</span>
</div>
</td>
<tr>
</table>
<button class="btn btn-primary col-sm-6" type="submit">sign up</button>
</form>
</div>
</div>
</body>
</html>
As described in the comment in html, when an error occurred in each field, I wrote that the frame of the text box turned red, but the result was that the frame did not turn red as shown below.
By the way, "has-error" is a Bootstrap class that makes the text box frame red.
When I checked the "Bootstrap 4 Migration Guide", there was the following description.
** [Changes from Bootstrap 3.x] Change the display style of each verification state to the style using the HTML5 form verification function .has-warning, .has-error, .has-success, .has-feedback, .form-control-feedback are obsolete As a fallback, .is-invalid and .is-valid classes can be used instead of server-side validation pseudo-classes. .was-validated No parent class required. ** **
URL:https://bootstrap-guide.com/components/forms?
Since Bootstrap 4, "has-error" has been abolished, and "is-invalid" seems to be provided as a function instead.
Write it in the input tag, not in the div tag.
signup.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/template}">
<head>
<meta charset="UTF-8"></meta>
<title>SignUp</title>
</head>
<!--User registration screen-->
<body>
<div layout:fragment="content">
<div class="col-sm-4 offset-sm-4">
<div class="page-header">
<h1>User registration screen</h1>
</div>
<form method="post" th:action="@{/signupUser}" th:object="${signupForm}">
<table class="table table-bordered table-hover">
<tr>
<td>
<div class="form-group">
<!--If an error occurs in the "userId" field of the model object "signupForm", add the class attribute and "is"-Make the area around the text box red with "invalid"-->
<input type="text" class="form-control" placeholder="Login ID" th:field="*{userId}"
th:classappend="${#fields.hasErrors('userId')}?'is-invalid'"/>
<span class="text-danger"
th:if="${#fields.hasErrors('userId')}"
th:errors="*{userId}">
userId error
</span>
</div>
</td>
<tr>
<tr>
<td>
<div class="form-group">
<!--If an error occurs in the "mailAddress" field of the model object "signupForm", add the class attribute and "is"-Make the area around the text box red with "invalid"-->
<input type="text" class="form-control" placeholder="mail address" th:field="*{mailAddress}"
th:classappend="${#fields.hasErrors('mailAddress')}?'is-invalid'"/>
<span class="text-danger"
th:if="${#fields.hasErrors('mailAddress')}"
th:errors="*{mailAddress}">
mailAddress error
</span>
</div>
</td>
<tr>
<tr>
<td>
<div class="form-group">
<!--If an error occurs in the "password" field of the model object "signupForm", add the class attribute and "is"-Make the area around the text box red with "invalid"-->
<input type="text" class="form-control" placeholder="password" th:field="*{password}"
th:classappend="${#fields.hasErrors('password')}?'is-invalid'"/>
<span class="text-danger"
th:if="${#fields.hasErrors('password')}"
th:errors="*{password}">
password error
</span>
</div>
</td>
<tr>
</table>
<button class="btn btn-primary col-sm-6" type="submit">sign up</button>
</form>
</div>
</div>
</body>
</html>
When I executed it, I was able to make the frame of the text box red when there was an input error, as shown below.
reference: https://www.e-pokke.com/blog/bootstrap4-invalid-feedback.html https://learning-collection.com/thymeleaf%E3%81%AE%E4%BD%BF%E3%81%84%E6%96%B9/
Recommended Posts