Home > front end >  How to validate the annotation @Email?
How to validate the annotation @Email?

Time:10-15

@Entity
@Table(name = "users")
public class Register {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Email
    private String email;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

If the value of getEmail() is not an email address, I get this error:

ERROR 17124 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction] with root cause

javax.validation.ConstraintViolationException: Validation failed for classes [*] during persist time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='must be a well-formed email address', propertyPath=email, rootBeanClass=class com.dynamicquatation.dq.components.register.Register, messageTemplate='{javax.validation.constraints.Email.message}'}

How can I validate that field? I tried it with if (data.getEmail() != null) {...} but I still get the same error.

This is another way how I tried to catch the error:

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class RegisterController {
    private final RegisterService registerService;

    public RegisterController(RegisterService registerService) {
        this.registerService = registerService;
    }

    @PutMapping(value = "register")
    Map<String, Object> register(@RequestBody Register data, MethodArgumentNotValidException exception) {
        return registerService.registerUser(data, exception);
    }
}
@Service
public class RegisterService {
    public Map<String, Object> registerUser(Register data, MethodArgumentNotValidException exception) {
        Map<String, Object> response = new HashMap<>();
        Map<String, String> errors = new HashMap<>();

        // Validate email
        System.out.println(exception.getFieldError("email"));

It gives me that error:

Controller [com.dynamicquatation.dq.components.register.RegisterController]

Method [java.util.Map<java.lang.String, java.lang.Object> com.dynamicquatation.dq.components.register.RegisterController.register(com.dynamicquatation.dq.components.register.Register,org.springframework.web.bind.MethodArgumentNotValidException)] with argument values:

[0] [type=com.dynamicquatation.dq.components.register.Register] [value=com.dynamicquatation.dq.components.register.Register@3f303f1a],

[1] [type=org.springframework.validation.BeanPropertyBindingResult] [value=org.springframework.validation.BeanPropertyBindingResult: 0 errors] ] with root cause

java.lang.IllegalArgumentException: argument type mismatch

CodePudding user response:

I agree with Alex by using @RequestBody @Valid Register data. But if you also want to show the error message, you will need to work with MethodArgumentNotValidException. Instead of using it in controller or service, you can use it in a class with a @ControllerAdvice annotation.

@ControllerAdvice
public class ValidationHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String, Object> response = new HashMap<>();
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            errors.put(((FieldError) error).getField(), error.getDefaultMessage());
            response.put("errors", errors);
        });
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}

That should respond:

{
    "errors": {
        "email": "must be a well-formed email address"
    }
}

If you want a custom error message, you can use

@Email(message = "Email is not valid")

CodePudding user response:

When receive the body, you have to call @Valid on it

@RequestBody @Valid Register data 

though in your example it's on an entity class, which from a functionality POV will work, but it's not a pattern you'd want if the project gets more complex.

  • Related