Bean Validation 的hibernate 实现

package des.tiny.entity;

import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public class TestVo {

	@RightCode(node = {"申购","赎回"},message = "必须是申购或赎回!")
	private String name;
	
	@Pattern(regexp = "[0-9]{1,2}",message = "must number between 0 and 99")
	private String age;

	public TestVo(String name, String age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "TestVo [name=" + name + ", age=" + age + "]";
	}
	
}

package des.tiny.entity;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Constraint(validatedBy = {RightCodeValidator.class})
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME) 
public @interface RightCode {
	String message() default ""; 
	String [] node() default{};
	Class<?>[] groups() default {}; 
	Class<? extends Payload>[] payload() default {}; 
}

package des.tiny.entity;

import java.util.Arrays;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class RightCodeValidator implements ConstraintValidator<RightCode, String>{

	private String[] ALL_STATUS;
	
	@Override
	public void initialize(RightCode arg0) {
		ALL_STATUS = arg0.node();
	}

	@Override
	public boolean isValid(String arg0, ConstraintValidatorContext arg1) {
		if(Arrays.asList(ALL_STATUS).contains(arg0)){
			return true;
		}
		return false;
	}

}

package des.tiny.main;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import des.tiny.entity.TestVo;

public class Main {

	public static void main(String[] args) {

		TestVo vo = new TestVo("申购", "300");
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();
		Set<ConstraintViolation<TestVo>> constraintViolations = validator
				.validate(vo);

		for (ConstraintViolation<TestVo> constraintViolation : constraintViolations) {
			System.out.println(constraintViolation.getMessage());
		}

	}
}


你可能感兴趣的:(Hibernate,validation)