5

I'm using validators in my spring controllers. If @RequestParam is required there is no problem, i can check String with @NotBlank. But if @RequestParam is optional, i can't use it with @NotBlank, because this parameter is optional and sometimes can be null. I want to validate @NotBlank if String is not null. Is there any constraint help me?

@RequestParam @NotBlank String name

working perfectly. I have problem with required=false if client don't send optional description parameter, validation fails.

@PatchMapping("/role/{id}") 
public ResponseEntity<?> updateRole(HttpServletRequest request, @PathVariable @Positive Integer id,
                                   @RequestParam @NotBlank String name,
                                   @RequestParam(required = false) @NotBlank String description)

I want to validate @NotBlank if description is not null.

`@RequestParam(required = false) @NotBlank String description`

If i use like that, i got "Input validation failed!".

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Edward D. Wilson
  • 351
  • 1
  • 4
  • 11
  • try to put `@Valid` annotation – dehasi Jan 31 '19 at 11:47
  • @dehasi i think, i don't need `@Valid` . I have `@Validated` annotation with my controller class and other validations works. But i tried `@RequestParam(required = false) @Valid @NotBlank String description` and it not works. – Edward D. Wilson Jan 31 '19 at 11:56

3 Answers3

2

You need to add a custom validator for this.

Interface

@Documented
@Constraint(validatedBy = YourValidator.class)
@Target({ ElementType.METHOD,ElementType.ANNOTATION_TYPE,ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface NotBlankIfPresent{

    String message() default "Error MEssage";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Your Validator Class

public class YourValidator implements ConstraintValidator<NotBlankIfPresent, String> {

    @Override
    public boolean isValid(String s, ConstraintValidatorContext context) {
        if (s == null) {
            return true;
        }
        
        return !s.isBlank();
    }

}
Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104
0

This is not right approach to validate @RequestParam. You have to validate in your code if it is blank then throw new IllegalArgumentException("{\"error\":\"The parameter is invalid\"}"

IMParasharG
  • 1,869
  • 1
  • 15
  • 26
  • 1
    Why this is not right approach? We generally use javax.constraints for validation. simple and easy. – Edward D. Wilson Jan 31 '19 at 12:15
  • @EdwardD.Wilson : please check my answer in similar context https://stackoverflow.com/questions/53997703/the-validators-validated-valid-do-not-work-with-spring-and-tomee/53998229#53998229 – IMParasharG Jan 31 '19 at 12:58
0

There is no point in using @RequestParam(required = false) and @NotBlank together. Here is how the @NotBlank annotation works.

a String field constrained with @NotBlank must be not null and the trimmed length must be greater than zero.

Maybe a workaround could be using a default value in your request param variable whenever you have required = false

Example:

@PatchMapping("/role/{id}") 
public ResponseEntity<?> updateRole(HttpServletRequest request, @PathVariable 
@Positive Integer id, @RequestParam @NotBlank String name,
@RequestParam(required = false, defaultValue = "adefaultvalue") @NotBlank String description) {
    if(description.equals("adefaultvalue") {
      // that means that the user did not send any value for this variable so you can 
     // add your validation logic here
    }
}

Please have in mind that the above code has not been tested

NickAth
  • 1,089
  • 1
  • 14
  • 35