原文:http://blog.csdn.net/neweastsun/article/details/49154337html
感謝做者!java
---------------------------------------------------------------------------------------------------git
Java開源驗證框架oval,功能很是強大,使用簡單;如今整理幫助文檔供你們參考,但願能獲得更多的反饋和使用經驗。web
Check if evaluating the expression in thespecified expression language returns true.正則表達式
檢查指定語言的表達式返回值是否爲true;這裏表達式是groovy。express
參數api |
說明數組 |
expr框架 |
表達式ide |
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;
主要參數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相反;
參數 |
說明 |
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
參數 |
說明 |
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;
}
}
參數 |
說明 |
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;
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;
參數 |
說明 |
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;
參數 |
說明 |
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;
參數 |
說明 |
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;
參數 |
說明 |
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
參數 |
說明 |
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
參數 |
說明 |
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 (""). |
沒有其餘特殊屬性
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
@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;
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 |
示例:
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 方法的參數,及被驗證值的類型 |
總結說明針對不一樣場景的主要使用那些註解。
@AsserURL、@Email、@Length、@MaxLength、@MinLength
@NotNull、@NotBlank、@NotEmpty、
@Digits、@HasSubstring
@Range、@Max、@Min、@NotNegative
@AssertFalse、@AssertTrue
@Size、@MaxSize、@MinSize、@MemberOf、@NotMemberOf
@Assert、@CheckWith、@NotMatchPatternCheck,@MatchPatternCheck、
@ValidateWithMethod
@Past和@Future不能驗證字符串類型的日期;自定義@CPast和@CFuture,都提供要給參數指定日期格式,默認爲:yyyy-MM-dd;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})
@Constraint(checkWith = CPastCheck.class)
public @interface CPast {
Stringmessage() default "日期必須小於如今.";
StringdateFormat() default "yyyy-MM-dd";
}
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;
}
}
總結驗證規則,能夠在設計時進行定義,自動生成對應的驗證語句,提升開發效率;和js驗證框架進行結合,實現web開發先後臺驗證設計保持一致,統一輩子成代碼;