OVAL验证框架帮助文档
目录
1. 注解说明
1.1、 @Assert
1.2、 @AssertFalse、@AssertTrue,@AssertNull
1.3、 @AssertURL
1.4、 @CheckWith
1.5、 @DateRange、@Future、@Past
1.6、 @Email
1.7、 @EqualToField,@Not EqualToField
1.8、 @HasSubstring
1.9、 @Length,@MaxLength,@MinLength
1.10、 @Size、@MinSize、@MaxSize
1.11、 @MemberOf、@NotMemberOf
1.12、 @NotBlank、@NotNull、@NotEmpty
1.13、 @NotNegative
1.14、 @Digits、@Range、@Max、@Min
1.15、 @NotMatchPatternCheck,@MatchPatternCheck
1.16、 @ValidateWithMethod
2. 使用总结
2.1. 字符类型
2.2. 数值类型
2.3. 布尔类型
2.4. 集合数组
2.5. 表达式或自定义
3. 自定义注解
3.1 定义注解
3.2 定义实现
4. maven依赖
java开源验证框架oval,功能非常强大,使用简单;
1. 注解说明
1.1、 @Assert
检查指定语言的表达式返回值是否为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
@AssertFalse检查值是否为假、@AssertTrue检查值是否为真,主要参数when、errorCode、message.
Note: 该验证当值为null时也满足;当然我们可以结合@NotNull来使用;
@AssertNull说明:检查值是否为空, 与@NotNull相反;
1.3、 @AssertURL
参数 | 说明 |
connect(boolean) | Specifies if a connection to the URL should be attempted to verify its validity. 是否发起连接进行尝试; |
检查值是否为有效的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 you might 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;
1.10、 @Size、@MinSize、@MaxSize
参数 | 说明 |
max |
|
min |
|
@MaxSize 和 @MinSize只有value属性;表示和value进行比较,判断array,map, 或者 collection大小;
min和max是@size的属性;
Check if the array,map, or collection
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 long serialVersionUID = 1L;
private String dateFormat;
public void configure(final CPast constraintAnnotation) {
super.configure(constraintAnnotation);
setDateFormat(constraintAnnotation.dateFormat());
}
public boolean isSatisfied(Object validatedObject, Object valueToValidate,
OValContext context, Validator validator) throws OValException {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
if(valueToValidate instanceof String) {
try {
Datedate = sdf.parse((String) valueToValidate);
return date.before(new Date());
}catch (ParseException e) {
e.printStackTrace();
super.setMessage("日期格式错误,无法验证,请修改成正确格式.");
return false;
}
}
return false;
}
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat= dateFormat;
}
}
4. maven依赖
<dependency>
<groupId>net.sf.oval</groupId>
<artifactId>oval</artifactId>
<version>1.81</version>
</dependency>