Home > Net >  Spring - @Valid not working after calling method
Spring - @Valid not working after calling method

Time:10-07

I wrote example of endpoints to understand the meaning of my question.

I realised that my tests didnt pass due to the @Valid annotation.

Eg. I got two endpoints if someone is hitting the old one there is a need to check if Email is set becuase it has a @NotBlank annotation. But when I'm asking my endpoint with a set email the @Valid is not executed I realised that after doing tests with invalid data. And I cannot set the @Valid in the oldPutContact because there are some contacts without email.

My question is why putContact didn't execute the @Valid annotation.

    @PutMapping(value = "/contact/{contactid}", )
    public String oldPutContact(@RequestBody Contact contact)
        if(StringUtils.isBlank(contact.getEmail())){
            contact.setEmail("[email protected]") ;
        }
        return putContact(contact);
    }
    @PutMapping(value = "/contact/update/{contactid}")
    public String putContact(@RequestBody @Valid Contact contact) {
        contactService.updateContact(contact);
    }

Imagine Contact Entity looks like this

 @Builder(toBuilder=true)
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Contact {

        private static final String SOME_PATTERN = "";
       private static final String SOME_EMAIL_PATTERN = "";
        private static final String SOME_PATTERN2 = "";
      
        @NotBlank
        private String id;

        @NotNull
        private Boolean isActive;

        @NotBlank
        @Pattern(regexp = SOME_PATTERN)
        private String name;

        @NotBlank
        @Pattern(regexp = SOME_PATTERN)
        private String surname;
        
       @NotBlank
        @Email(regexp = SOME_EMAIL_PATTERN)
        private String email;

        @NotBlank
        @Pattern(regexp = SOME_PATTERN2)
        private String telephone;

    }

CodePudding user response:

Firstly you should define the validation rule for your parameters. For example(Note the NotBlank annotation):

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotBlank(message = "Name is mandatory")
    private String name;

    @NotBlank(message = "Email is mandatory")
    private String email;

    // standard constructors / setters / getters / toString
    
}

Then you can use the valid annotation in rest api controller. Like this:

@RestController
public class UserController {

    @PostMapping("/users")
    ResponseEntity<String> addUser(@Valid @RequestBody User user) {
        // persisting the user
        return ResponseEntity.ok("User is valid");
    }

    // standard constructors / other methods

}

You may not define the validation rule. So spring doesn’t know how to validate the parameter.

Please refer to Spring validation for further information.

----By reading the comment from @nusia, add the following description.

From the sample code "public String putContact(@RequestBody @Valid String contact)", I can't see where you define the @NotBlank annotation to parameter String contact, or did you mean the type of argument "contact" is not string? If the type of "contact" is a defined entity and its email field has the NotBlank annotation. Then calling your new endpoint "putContact" from HTTP PUT request will fire the spring validation, but if you mean you call the new method "putContact" from your old method "oldPutContact" the spring validation will not be fired, the reason is similar to Call spring annotation method from same class.

  • Related