Hibernate Validator交叉字段验证(JSR 303)Hibernate Validator 4.x中是否有交叉字段验证的实现(或第三方实现)?如果不是,实现交叉字段验证器的最干净的方法是什么?例如,如何使用API来验证两个bean属性是否相等(例如验证密码字段与密码验证字段匹配)。在注释中,我希望类似于:public class MyBean {
@Size(min=6, max=50)
private String pass;
@Equals(property="pass")
private String passVerify;}
3 回答
缥缈止盈
TA贡献2041条经验 获得超4个赞
public class MyBean {
@Size(min=6, max=50)
private String pass;
private String passVerify;
@AssertTrue(message="passVerify field should be equal than pass field")
private boolean isValid() {
return this.pass.equals(this.passVerify);
}}isValid
森栏
TA贡献1810条经验 获得超5个赞
package com.moa.podium.util.constraints;import static java.lang.annotation.ElementType.*;import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.Target;
import javax.validation.Constraint;import javax.validation.Payload;@Target({TYPE, ANNOTATION_TYPE})@Retention(RUNTIME)
@Constraint(validatedBy = MatchesValidator.class)@Documentedpublic @interface Matches {
String message() default "{com.moa.podium.util.constraints.matches}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String field();
String verifyField();}package com.moa.podium.util.constraints;import org.mvel2.MVEL;import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;public class MatchesValidator implements ConstraintValidator<Matches, Object> {
private String field;
private String verifyField;
public void initialize(Matches constraintAnnotation) {
this.field = constraintAnnotation.field();
this.verifyField = constraintAnnotation.verifyField();
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
Object fieldObj = MVEL.getProperty(field, value);
Object verifyFieldObj = MVEL.getProperty(verifyField, value);
boolean neitherSet = (fieldObj == null) && (verifyFieldObj == null);
if (neitherSet) {
return true;
}
boolean matches = (fieldObj != null) && fieldObj.equals(verifyFieldObj);
if (!matches) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("message")
.addNode(verifyField)
.addConstraintViolation();
}
return matches;
}}@Matches(field="pass", verifyField="passRepeat")public class AccountCreateForm {
@Size(min=6, max=50)
private String pass;
private String passRepeat;
...}添加回答
举报
0/150
提交
取消
