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
提交
取消
