hibernate validation內置注解及自定義注解


 1 Bean Validation 中內置的 constraint         
 2 @Null   被注釋的元素必須為 null    
 3 @NotNull    被注釋的元素必須不為 null    
 4 @AssertTrue     被注釋的元素必須為 true    
 5 @AssertFalse    被注釋的元素必須為 false    
 6 @Min(value)     被注釋的元素必須是一個數字,其值必須大於等於指定的最小值    
 7 @Max(value)     被注釋的元素必須是一個數字,其值必須小於等於指定的最大值    
 8 @DecimalMin(value)  被注釋的元素必須是一個數字,其值必須大於等於指定的最小值    
 9 @DecimalMax(value)  被注釋的元素必須是一個數字,其值必須小於等於指定的最大值    
10 @Size(max=, min=)   被注釋的元素的大小必須在指定的范圍內    
11 @Digits (integer, fraction)     被注釋的元素必須是一個數字,其值必須在可接受的范圍內    
12 @Past   被注釋的元素必須是一個過去的日期    
13 @Future     被注釋的元素必須是一個將來的日期    
14 @Pattern(regex=,flag=)  被注釋的元素必須符合指定的正則表達式    
15     
16 Hibernate Validator 附加的 constraint    
17 @NotBlank(message =)   驗證字符串非null,且長度必須大於0    
18 @Email  被注釋的元素必須是電子郵箱地址    
19 @Length(min=,max=)  被注釋的字符串的大小必須在指定的范圍內    
20 @NotEmpty   被注釋的字符串的必須非空    
21 @Range(min=,max=,message=)  被注釋的元素必須在合適的范圍內

自定義注解:

Employee.java
 
package org.lxl.spring.form.model;
 
public class Employee {
private int id;
private String name;
private String role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
 
}
 
Employee是一個標准的java bean,我們使用Validate接口的實現類來驗證這個類。
 
自定義驗證實現
 
Phone.java
package org.lxl.spring.form.validator;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
 
import javax.validation.Constraint;
import javax.validation.Payload;
@Documented
@Constraint(validatedBy = PhoneValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String message() default "{Phone}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
 
大多數的部分是樣板式代碼與jsr - 303規范確認。最重要的部分是@Constraint注釋,我們提供的類即PhoneValidator將用於驗證。
PhoneValidator.java
package org.lxl.spring.form.validator;
 
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
 
public class PhoneValidator implements ConstraintValidator<Phone,String> {
 
@Override
public void initialize(Phone paramA) {
}
 
@Override
public boolean isValid(String phoneNo, ConstraintValidatorContext ctx) {
if(phoneNo == null){
return false;
}
//validate phone numbers of format "1234567890"
if(phoneNo.matches("\\d{10}")) return true;
//validate phone number with -, . or spaces
else if(phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}}")) return true;
//validating phone number with extension length from 3 to 5
else if(phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}")) return true;
//validating phone number where area code is in braces()
else if(phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")) return true;
//return false if nothing matches the input
else return false;
}
}
我們應該實現javax.validation.ConstraintValidatorinterface jsr - 303規范驗證器實現。如果我們使用數據源等一些資源,我們可以在initialize()方法初始化它們。驗證方法是isValid和其他它返回true,如果數據是有效的它應該返回false。
 
EmployeeFormValidator.java
package org.lxl.spring.form.validator;
 
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
 
import org.lxl.spring.form.model.Employee;
 
public class EmployeeFormValidator implements Validator{
//which objects can be validated by this validator
@Override
public boolean supports(Class<?> paramClass) {
return Employee.class.equals(paramClass);
}
 
@Override
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "id.required");
Employee emp = (Employee) obj;
if(emp.getId() <=0){
errors.rejectValue("id", "negativeValue",new Object[]{"'id'"},"id can't be negative");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "role", "role.required");
}
}
EmployeeFormValidator是自定義驗證實現類。support()方法是validator接口中規定的方法,告訴Spring框架,哪個類能使用這個驗證。
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM