OVAL验证框架帮助文档

OVAL验证框架帮助文档
java开源验证框架oval,功能非常强大,使用简单;现在整理帮助文档供大家参考,希望能得到更多的反馈和使用经验。

1.  注解说明
1.1、  @Assert
Check if evaluating the expression in thespecified expression language returns true.

检查指定语言的表达式返回值是否为true;这里表达式是groovy。

参数

说明

expr

表达式

lang

指明脚本语言

errorCode

错误编码(共有属性)

(可以修改成自己的异常编码串)

net.sf.oval.constraint.Assert(默认值)

message

错误描述(共有属性)

when

前置条件(共有属性)

 

 

示例:下面验证登录名必须是用户名或用户编码; when表示前置条件;

@Assert(expr="_value==_this.userName || _value ==_this.userCode" ,

lang="groovy",message="login name error." , ,when="groovy:_this.status>0")

private String loginName;

private int status;

 

1.2、   @AssertFalse、@AssertTrue,@AssertNull
主要参数when、errorCode、message

Check if the value is false. (检查值是否为假或真)

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

该验证当值为null时也满足;当然我们可以结合@NotNull来使用;

@AssertTrue的说明如下,与上面一致,不再翻译;

Check if the value is true.

 

Note: Thisconstraint is also satisified when the value to validate is null, therefore youmight also need to specified @NotNull

 

@AssertNull说明:Check if null. 与@NotNull相反;

1.3、  @AssertURL
参数

说明

connect(boolean)

Specifies if a connection to the URL should be attempted to verify its validity.

是否发起连接进行尝试;

 

Check if the value is a valid URL. (检查值是否为有效的URL)

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

 

1.4、  @CheckWith
参数

说明

Class<? extendsCheckWithCheck.SimpleCheck>

value

          Check class to use for validation.

指明验证类

ignoreIfNull        

 this constraint will be ignored if the value to check is null

说明:

Check the value by a method of the sameclass that takes the value as argument and returns true if valid and false ifinvalid.

使用net.sf.oval.constraint.CheckWithCheck.SimpleCheck实现该接口的类中isSatisfied方法来判断,返回true有效,false无效;如果实现类是内部的,必须为静态类。

 

示例:验证User类中的age字段

@CheckWith(value=CheckAge.class,message="agemust in (18~65)")

private int age;

 

验证类如下:

publicclass CheckAge implements CheckWithCheck.SimpleCheck {
    private static final long serialVersionUID =1L;

 

    @Override

    public boolean isSatisfied(ObjectvalidatedObject, Object value) {
        User user = (User)validatedObject;

        int age = user.getAge();

       

        if(age <18 || age > 65)

            return false;

        else

            return true;

    }

}

 

 

1.5、  @DateRange、@Future、@Past
参数

说明

min

         /**

          * The upper date compared against in the format specified with the dateFormat parameter.

          * If not specified then no upper boundary check is performed.<br>

          * Special values are:

          * <ul>

          * <li><code>now</code>

          * <li><code>today</code>

          * <li><code>yesterday</code>

          * <li><code>tomorrow</code>

          * </ul>

          */

max     

         /**

          * The lower date compared against in the format specified with the dateFormat parameter.

          * If not specified then no lower boundary check is performed.<br>

          * Special values are:

          * <ul>

          * <li><code>now</code>

          * <li><code>today</code>

          * <li><code>yesterday</code>

          * <li><code>tomorrow</code>

          * </ul>

          */

 

 

Check if the date is within the a daterange.

Note: This constraint is also satisfied when the value to validate isnull, therefore you might also need to specified @NotNull

 

示例:字符串类型一样可以;

@Future(message="date isfuture.") 不能验证字符串,改用自定义类型@CFuture

@Past(message="date is past.")    不能验证字符串,改用自定义类型@CPast

 

@DateRange可以验证字符串类型,请查看源码验证

@DateRange(min="2010-10-01",max="now",message="dateis error.")

private String birthday;

1.6、  @Email
Check if the value is a valid e-mailaddress. The check is performed based on a regular expression.

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

示例:

@Email(message="email is error.")

private String email;

 

1.7、  @EqualToField,@Not EqualToField
参数

说明

boolean useGetter

useGetter default false;

 

 

Check if value equals the value of thereferenced field.

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

 

示例:检查userCode是否和userName相等;使用get方法。

 

@EqualToField(value="userName",message="mustequals userName",useGetter=true)

private String userCode;

 

示例与上面相反;

@NotNull(message="not null")

@NotEqualToField(value="userCode",message="can'tequals userCode")

private String userName;

 

1.8、  @HasSubstring
参数

说明

value

需要给的子串

 

ignoreCase(boolean)

ignoreCase default false;

 

Check if the string contains a certainsubstring.

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

 

示例:

         @HasSubstring(value="san",ignoreCase=true,message="mustcontains 'san'")

         privateString userCode;

 

1.9、   @Length,@MaxLength,@MinLength
参数

说明

max

最大长度,默认为:Integer.MAX_VALUE

 

min

默认值为0

@MaxLength和 @MinLength只有value属性;表示和value进行比较;

min和max是@length的属性;

Checkif the string representation has certain length. 检查字符串的长度

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

 

示例:检查长度,汉字算一个;

@Length(max=10,message="最大长度不能超过10")

private String code;

 

源码逻辑参考:

final int len =valueToValidate.toString().length();

return len >= min && len <=max;

 

 

 

1.10、          @Size、@MinSize、@MaxSize
参数

说明

max

 

min

 

@MaxSize 和 @MinSize只有value属性;表示和value进行比较,判断array,map, or collection大小;

min和max是@size的属性;

 

Check if the array,map, or collection has the given size. For objects of other types thelength of their String representation will be checked. 检查array、map或集合的大小;其他类型的对象检查对应字符串的长度;建议字符长度使用@Length验证。

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

 

 

1.11、          @MemberOf、@NotMemberOf
参数

说明

value 字符串数组

 

ignoreCase

默认值false

 

Check if the string representation iscontained in the given string array.

检查值是否包含在给定的数组中;@NotMemberOf实现相反效果;

 

Note: This constraint is also satisfiedwhen the value to validate is null, therefore you might also need to specified@NotNull

 

1.12、          @NotBlank、@NotNull、@NotEmpty
参数

说明

NotBlank

Check if the string representation is not empty and does not only contain white spaces.

NotNull

Check if not null.

NotEmpty

Check if the string representation is not empty ("").

 

没有其他特殊属性

 

 

1.13、          @NotNegative
Check if the number is greater or equalzero. 检查值是否为非负数

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

 

1.14、          @Digits、@Range、@Max、@Min
@Range 有max和min 属性,检查数值类型的范围;

Check if the number is in the given range.(和Double进行比较)

@Min

Check if the number is greater than orequal to X.

@Max

Check if the number is smaller than orequal to X.

 

@Digits

Check if the String representation has thegiven max/min number of integral and fractional digits.

检查字符串形式的数字范围,对应属性如下

maxFraction = Integer.MAX_VALUE;

maxInteger = Integer.MAX_VALUE;

minFraction = 0;

minInteger = 0;

 

1.15、          @NotMatchPatternCheck,@MatchPatternCheck
Check if the specified regular expressionpattern is or not matched. 正则表达式验证

 

Note: Thisconstraint is also satisfied when the value to validate is null, therefore youmight also need to specified @NotNull

 

参数

说明

pattern

          The regular expression(s) that must match or not match

示例:

1.16、          @ValidateWithMethod
Check the value by a method of the sameclass that takes the value as argument and returns true if valid and false ifinvalid.

验证值作为参数,使用同一个类的某个方法返回值的布尔值进行验证;

方法必须是和验证值在同一类中。

 

参数

说明

methodName

String

name a the single parameter method to use for validation

         

Class<?>          parameterType

type of the method parameter 方法的参数,及被验证值的类型

 

2.  使用总结
总结说明针对不同场景的主要使用那些注解。

2.1.          字符类型
@AsserURL、@Email、@Length、@MaxLength、@MinLength

@NotNull、@NotBlank、@NotEmpty、

@Digits、@HasSubstring

2.2.          数值类型
@Range、@Max、@Min、@NotNegative

2.3.          布尔类型
@AssertFalse、@AssertTrue

2.4.          集合数组
@Size、@MaxSize、@MinSize、@MemberOf、@NotMemberOf

2.5.          表达式或自定义
@Assert、@CheckWith、@NotMatchPatternCheck,@MatchPatternCheck、

@ValidateWithMethod

 

3.  自定义注解
@Past和@Future不能验证字符串类型的日期;自定义@CPast和@CFuture,都提供要给参数指定日期格式,默认为:yyyy-MM-dd;

 

3.1             定义注解
 

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})

@Constraint(checkWith = CPastCheck.class)

public @interface CPast {
 

         Stringmessage()    default "日期必须小于现在.";

         StringdateFormat() default "yyyy-MM-dd";

}

3.2             定义实现
 

public class CPastCheck extends AbstractAnnotationCheck<CPast> {
         private static final longserialVersionUID = 1L;

         private StringdateFormat;

 

         public voidconfigure(final CPast constraintAnnotation) {
                   super.configure(constraintAnnotation);

                   setDateFormat(constraintAnnotation.dateFormat());

         }

 

         public booleanisSatisfied(Object validatedObject, Object valueToValidate,

                            OValContextcontext, Validator validator) throws OValException {
                   SimpleDateFormatsdf = new SimpleDateFormat(dateFormat);

 

                   if(valueToValidate instanceof String) {
                            try {
                                     Datedate = sdf.parse((String) valueToValidate);

                                     returndate.before(new Date());

                            }catch (ParseException e) {
                                     e.printStackTrace();

                                     super.setMessage("日期格式错误,无法验证,请修改成正确格式.");

                                     returnfalse;

                            }

                   }

                   return false;

         }

 

         public StringgetDateFormat() {
                   returndateFormat;

         }

 

         public voidsetDateFormat(String dateFormat) {
                   this.dateFormat= dateFormat;

         }

}

 

4.  记录点滴
总结验证规则,可以在设计时进行定义,自动生成对应的验证语句,提高开发效率;和js验证框架进行结合,实现web开发前后台验证设计保持一致,统一生成代码;
————————————————

原文链接:https://blog.csdn.net/neweastsun/article/details/49154337/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值