I want to make the frame of the text box red when there is an input error

Introduction

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.

environment

OS: macOS Catalina 10.15.6 JDK:14.0.1 Spring Boot 2.3.3 jquery 3.3.1-1 bootstrap 4.2.1

① When checking the input

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.

② Create input form (before modification)

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.

スクリーンショット 2020-10-21 13.00.49.png

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.

③ Correction of input form

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.

スクリーンショット 2020-10-21 13.28.10.png

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

I want to make the frame of the text box red when there is an input error
I want to display an error message when registering in the database
Rails6 I want to make an array of values with a check box
I tried to solve the Ruby karaoke machine problem (there is an example of the answer)
I tried to solve the Ruby bonus drink problem (there is an example of the answer)
How to output the value when there is an array in the array
I want to limit the input by narrowing the range of numbers
I want to control the default error message of Spring Boot
I tried to solve the Ruby bingo card creation problem (there is an example of the answer)
I want to make an ios.android app
[JavaScript] How to display an alert when there is an input form omission
I want to know the JSP of the open portlet when developing Liferay
[Java] I want to make it easier because it is troublesome to input System.out.println.
I want to output the day of the week
I want to var_dump the contents of the intent
[Ruby] Meaning of &. How to avoid the error when the receiver (object) is nil
[Ruby] I want to make a program that displays today's day of the week!
After installing'devise''bootstrap' of gemfile with rails, what to do when url is an error
When the hover of Eclipse is hard to see
I want to know the answer of the rock-paper-scissors app
I want to display the name of the poster of the comment
When I think about the 402 error that suddenly appeared in the middle of the introduction of PAY.jp, there was an unexpected place
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
I want you to put the story that the error was solved when you stabbed the charger in the corner of your head
I want to be aware of the contents of variables!
I want to return the scroll position of UITableView!
I want to find out which version of java the jar file I have is available
I found no way to get the error code when I received an exception on Android
I got an error! * There is no interactive request template
I want to expand the clickable part of the link_to method
I want to make a specific model of ActiveRecord ReadOnly
I want to change the log output settings of UtilLoggingJdbcLogger
The idea of cutting off when the error is not resolved
When you want to change the MySQL password of docker-compose
What is an immutable object? [Explanation of how to make]
I want to narrow down the display of docker ps
I want to return multiple return values for the input argument
[Ruby] I want to reverse the order of the hash table
I want to temporarily disable the swipe gesture of UIPageViewController
I want to judge the necessity of testing by comparing the difference of class files when refactoring Java
Throw an exception and catch when there is no handler corresponding to the path in spring
I want to understand the flow of Spring processing request parameters
The story of Collectors.groupingBy that I want to keep for posterity
Want to know what Ruby n is the power of 2? (Power judgment of 2)
I made a gem to post the text of org-mode to qiita
I want to change the value of Attribute in Selenium of Ruby
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]
A memo when you want to clear the time part of the calendar
What I thought when passing the user input value to the Service class
I want to display the number of orders for today using datetime.
[Rails] About the error when displaying the screen due to the autofocus of the form
Recorded because I was addicted to the standard input of the Scanner class
When the appearance of the input form is broken on the page after rendering
[Ruby] I want to extract only the value of the hash and only the key
Error when the member of Entity class used in SpringWebFlux is final
I want to get the IP address when connecting to Wi-Fi in Java
I tried to make full use of the CPU core in Ruby
I want to get the field name of the [Java] field. (Old tale tone)
I want you to use Enum # name () for the Key of SharedPreference
[Rails] What to do when the Refile image is not displayed when writing the processing at the time of Routing Error
What to do if you get an "A server is already running." Error when you try to start the rails server