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 class="invalid-feedback"
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