Malena T
Malena T

Reputation: 371

Validation not performed in a Spring controller

I want to use annotations in classes. I use javax.validation.constrants.* for annotations.

public final class EmailCredential implements Serializable {

    private static final long serialVersionUID = -1246534146345274432L;

    @NotBlank(message = "Sender must not be empty.")
    @Email
    private final String sender;

    @NotBlank(message = "Subject must not be empty.")
    private final String subject;

/// getters setters

}

None of them are working as expected. Meaning that when a below API gets called, annotations should throw error if annotated field is invalid. It looks like there is no annotation to check fields. How properly can I use annotations in a normal class?

controller:

@PostMapping(value = "/email/credentials", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> emailCredentials(@RequestBody EmailCredential emailCredential) {
        return emailService.setCredentials(emailCredential);
    }

Upvotes: 1

Views: 1761

Answers (2)

davidxxx
davidxxx

Reputation: 131336

In your case the validation has to be specified to be triggered.
So add the @Valid annotation on the parameter(s) that you want to validate such as :

import javax.validation.Valid;
// ...
@PostMapping(value = "/email/credentials", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> emailCredentials(@RequestBody @Valid EmailCredential emailCredential) {
        return emailService.setCredentials(emailCredential);
    }

Upvotes: 2

Mickael
Mickael

Reputation: 4558

According to Spring Boot official documentation : Validating Form Input

You should indicate that your EmailCredential need to be validated using the annotation @Valid

Here's an example from documentation :

package hello;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Controller
public class WebController implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/results").setViewName("results");
    }

    @GetMapping("/")
    public String showForm(PersonForm personForm) {
        return "form";
    }

    @PostMapping("/")
    public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "form";
        }

        return "redirect:/results";
    }
}

Upvotes: 2

Related Questions