Java standart bir Bean Validation API'ye sahiptir.

beanvalidation.org

pom.xml

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


Çok fazla annotationu var sadece basit olanları yazacağım.

  1. @NotNull -> Annotationa sahip olunan field'ın null olup olmadığını kontrol eder.
  2. @Min -> Annotationa sahip olunan bir sayının => verilen değerden büyük mü küçük mü kontrol eder.
  3. @Max -> Annotationa sahip olunan bir sayının =< verilen değerden küçük mü büyük mü kontrol eder.
  4. @Size -> Annotationa sahip olunan field'ın size (boyutunu) kontrol eder.
  5. @Pattern -> Annotationa sahip olunan field'ın verilen regular expression patterinin uyup uymadığını kontrol eder.
  6. @Future/@Past -> Tarih aralığının gelecek ve geçmişteki tarih aralığında mı değil mi kontrol eder.



Teacher.java

public class Teacher {
 
    private Long id;
    @NotNull
    @Size(min = 1,message = "isim zorunludur!")
    private String firstName;
    private String lastName;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
}


TeacherController.java

@Controller
public class TeacherController {
    @RequestMapping(path = "/showForm", method = RequestMethod.GET)
    public String getForm(Model theModel) {
        Teacher teacher = new Teacher();
        theModel.addAttribute("teacher", teacher);
        return "show-form";
    }
    @RequestMapping(path = "/sendForm", method = RequestMethod.POST)
    public String sendForm(@Valid @ModelAttribute("teacher") Teacher teacher,BindingResult theBindingResult, Model theModel) {
        if (theBindingResult.hasErrors()){
            return "show-form";
        }
        System.out.println("Öğretmen : " + teacher.getFirstName());
        theModel.addAttribute("message", "Öğretmen eklendi");
        return "success";
    }
}


show-form.html


<!DOCTYPE html>
<html xmlns:th='http://www.thymeleaf.org'>
    <head>
        <title>Show Form</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p th:text='${message}'/>
        <form action="#" th:action='@{/sendForm}' method="POST" th:object='${teacher}'>
            <label>İsim </label><br/>
            <input type='text' th:field='*{firstName}'/>
            <span th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"/>
            <br/>
            <label>Soyisim </label><br/>
            <input type='text' th:field='*{lastName}'/>
            <input type='submit' value='Kaydet'/>
        </form>
    </body>
</html>


success.html

<!DOCTYPE html>
<html xmlns:th='http://www.thymeleaf.org'>
    <head>
        <title>Success</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <span th:text='${teacher.firstName}'/>
    </body>
</html>



Eğer ki biz boşluk girersek değeri geçer yani herhangi bir sıkıntı yokmuş gibi devam eder halbuki whitespaces'leri de trim edip silmemiz gerekir bunun için öncelikle pre-processeor olarak çalışan @InitBinder annotationunu kullanabiliriz.

@InitBinder pre-process olarak bizim controllerımıza gelen her isteği işleyecektir. Hangi methodun çalışmasını istersek onun üstüne @InitBinder yerleştirmemiz gerekir.

Bunu da controllerımıza ekleyebiliriz.

@InitBinder
public void initBinder(WebDataBinder dataBinder){
    StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
    dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
}