【问题标题】:How to validate non-required RequestParam is not blank?如何验证非必需的 RequestParam 不为空?
【发布时间】:2019-06-24 20:56:46
【问题描述】:

我在我的 spring 控制器中使用验证器。如果需要@RequestParam 没有问题,我可以使用@NotBlank 检查字符串。但是如果@RequestParam 是可选的,我不能将它与@NotBlank 一起使用,因为这个参数是可选的,有时可以为空。 如果 String 不为空,我想验证 @NotBlank。有什么限制可以帮我吗?

@RequestParam @NotBlank String name

完美运行。我对required=false 有疑问 如果客户端不发送可选的描述参数,验证失败。

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

如果描述不是null,我想验证@NotBlank。

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

如果我这样使用,我会得到“输入验证失败!”。

【问题讨论】:

  • 尝试把@Valid注解
  • @dehasi 我想,我不需要 @Valid 。我的控制器类和其他验证工作有@Validated 注释。但我尝试了@RequestParam(required = false) @Valid @NotBlank String description,但它不起作用。

标签: java spring validation spring-restcontroller


【解决方案1】:

您需要为此添加自定义验证器。

界面

@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 {};
}

您的验证器类

public class YourValidator implements ConstraintValidator<NotBlankIfPresent, String> {

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

}

【讨论】:

    【解决方案2】:

    这不是验证@RequestParam 的正确方法。你必须在你的代码中验证 如果为空则throw new IllegalArgumentException("{\"error\":\"The parameter is invalid\"}"

    【讨论】:

    • 为什么这不是正确的方法?我们一般使用 javax.constraints 进行验证。简单易行。
    • @EdwardD.Wilson :请在类似的情况下检查我的答案stackoverflow.com/questions/53997703/…
    【解决方案3】:

    将@RequestParam(required = false) 和@NotBlank 一起使用是没有意义的。 以下是@NotBlank 注释的工作原理。

    使用@NotBlank 约束的字符串字段必须不为空,并且修剪后的长度必须大于零。

    当你有required = false

    例子:

    @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
        }
    }
    

    请注意以上代码未经测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 2019-11-11
      • 2019-01-22
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多