Search code examples
spring-bootthymeleaf

how to validate email spring boot thymeleaf


I Want to validate e-mail when user want to register at my website. I set @NotBlank and @Email annotations, made @Valid annotation at post method, but I don't know how to make it work properly. At /register endpoint application shows error500. How can I change my code to make it work? Username shouldn't register with blank or incorrect email, but I can't solve it.

AppUser class:

@Data
@Entity
public class AppUser implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    @NotBlank(message = "login is required")
    private String username;
    @NotBlank(message = "password is required")
    private String password;
    private String role;
    @Column(unique = true)
    @Email(message = "Wrong e-mail")
    private String email;
    private String phone;

    public AppUser() {
    }

UserController class:

@Controller
public class UserController {


    @GetMapping("register")
    public String register(Model model) {
        model.addAttribute("user", new AppUser());
        return "register";
    }

    @PostMapping("/registerOk")
    public String registerOk(@Valid AppUser appUser, Errors errors) {
        if (errors.hasErrors()) {
            return "register";
        }
        userService.addUser(appUser);
        return "redirect:register?success";
    }
}

My register.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>Rejestracja</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/index.css}"/>
</head>
<body>

<form class="box" th:action="@{/registerOk}" method="post">
    <div th:if="${param.success}">
        <div class="alert alert-info"><span style="color: white">Register is sucessful, check your e-mail adress.</span></div>
    </div>
    <h1>Register new account: </h1>
    <input type="text" name="username" placeholder="login">
<span class="validationError"
            th:if="${#fields.hasErrors('username')}"
            th:errors="*{username}">Username Error</span>
    <input type="password" name="password" placeholder="password" id="hide">
    <input type="text" name="email" placeholder="E-Mail">
    <input type="text" name="phone" placeholder="phone number">
    <input type="submit" value="Register me!">
    <div class="form-group">
        <span style="color: white">Already registered? <a href="/" th:href="@{/login}">Login</a></span>
    </div>
</form>

</body>
</html>

Solution

  • Use type="email" instead of text.

    <input type="email" name="email" placeholder="E-Mail">
    

    Use required if you would like the input field as mandatory input.

    <input type="email" name="email" placeholder="E-Mail" required>