Edward D. Wilson
Edward D. Wilson

Reputation: 361

How to validate non-required RequestParam is not blank?

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!".

Upvotes: 6

Views: 12073

Answers (3)

Niraj Sonawane
Niraj Sonawane

Reputation: 11075

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();
    }

}

Upvotes: 2

NickAth
NickAth

Reputation: 1112

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

Upvotes: 0

IMParasharG
IMParasharG

Reputation: 1895

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\"}"

Upvotes: 0

Related Questions