• No validator could be found for constraint ‘javax.validation.constraints.Pattern‘ validating type ‘j


    原文链接: https://blog.csdn.net/wangxuelei036/article/details/107079783

    今天使用validation中的 @Pattern 突然报错,提示 pattern 没有对应的校验器去验证Integer类型参数,什么鬼?

    javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Integer'. Check configuration for 'age'

    看看代码

    这里想通过正则去验证以下年龄是否在我们自定义的规则里面

    通过各种尝试和查阅终于得到答案

    原来是 项目中使用的校验注解所支持的数据类型与实体中字段的类型不符合。意思就是该类型上面无法使用这个注解。

    例:在Integer类型的字段上使用@NotEmpty,@Pattern 都不行 因为支持的是字符串类型字段,这样子使用肯定是会报错的。

    那么我该怎么办呢?

    解决方法:

    (1)换个校验注解,或者不使用校验注解
    例: 将Integer类型的字段上使用的@NotEmpty @Pattern 换成@NotNull,然后再在代码中进行校验
    (2)将Integer 类型转为 String 类型,如果允许的话,又或者单独冗余一个String字段用于校验,一个字段用于业务
    (3)直接放开校验,在代码层去进行保证
    (4)自定义一个校验器进行处理
    注:@Pattern 只能校验有值时候正则是否满足,不能校验空的问题,如果传入的参数为空,默认是正确的


    /**
    * @author Hardy Ferentschik
    */
    public class PatternValidator implements ConstraintValidator<Pattern, CharSequence> {
    ........
    public boolean isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext) {
    if ( value == null ) {
    return true;
    }
    Matcher m = pattern.matcher( value );
    return m.matches();
    }
    }
    如果你想要判断不能为空,同时满足正则可以进行组合注解验证

  • 相关阅读:
    Linux用户配置文件、口令配置文件、组配置文件
    Linux忘记Root密码怎么找回
    Linux运行级别及解释
    Maven获取resources的文件路径、读取resources的文件
    常见状态码100、200、300、400、500等
    JVM内存模型
    tcl使用小结
    MFQ&&PPDCS
    总结下自己在工作中有关联的TCP/IP协议
    二层交换机和三层交换机
  • 原文地址:https://www.cnblogs.com/fswhq/p/16262255.html
Copyright © 2020-2023  润新知