Home > database >  Spring Validation with Kotlin, Javax & Jakarta & Thymeleaf
Spring Validation with Kotlin, Javax & Jakarta & Thymeleaf

Time:12-03

I'm trying to validate my fields in spring MVC, I tried several ways, but none of them worked.

I used
implementation("org.springframework.boot:spring-boot-starter-validation") and then implementation("javax.validation:validation-api:2.0.1.Final")

I annotated the classes

@Data
data class Taco(
    @NotBlank
    @Size(min = 5, message = "Name must be at least 5 characters long")
    var name: String = "",
    @NotEmpty
    @Size(min = 1, message = "You must choose at least one ingredient")
    var ingredient: MutableList<Ingredients> = mutableListOf()
)

prepared the controller

  @PostMapping
    fun processTaco(
        @Valid taco: Taco,
        bindingResult: BindingResult,
        @ModelAttribute tacoOrder: TacoOrder,
    ): String {
        //In case there are errors based on the data object validations, return to the design page.
        if (bindingResult.hasErrors()) return "design"
        tacoOrder.addTaco(taco)
        println("Processing Taco:$taco")
        return "redirect:/orders/current"
    }

and implemented the design

<div>
        <h3>Name your taco creation:</h3>
        <input type="text" th:field="*{name}"/>
        <span 
              th:if="${#fields.hasErrors('name')}"
              th:errors="*{name}">name Error</span>
        <br/>
        <button>Submit Your Taco</button>
    </div>

but couldn't get a single field to be validated against the conditions... how to do that?

Regards

CodePudding user response:

well, after several tries, I made the validation check within the controller this way

 @PostMapping
    fun processTaco(
        taco: Taco,
        bindingResult: BindingResult,
        @ModelAttribute tacoOrder: TacoOrder,
    ): String {
        //In case there are errors based on the data object validations, return to the design page.
        checkTaco(taco, bindingResult)
        if (bindingResult.hasErrors()) return "design"
        tacoOrder.addTaco(taco)
        println("Processing Taco:$taco")
        return "redirect:/orders/current"
    }

    private fun checkTaco(taco: Taco, bindingResult: BindingResult) {
        if (taco.name.length < 5) bindingResult.addError(FieldError("name", "name", "Name Should be longer than 5 Characters."))
        if (taco.ingredient.isEmpty()) bindingResult.addError(FieldError("taco", "ingredient", "You should have at least once ingredient."))
    }

hopefully it will be useful to someone.

  • Related