呼如林
2019-06-19 10:24:30
Hibernate Validator交叉字段驗(yàn)證(JSR 303)Hibernate Validator 4.x中是否有交叉字段驗(yàn)證的實(shí)現(xiàn)(或第三方實(shí)現(xiàn))?如果不是,實(shí)現(xiàn)交叉字段驗(yàn)證器的最干凈的方法是什么?例如,如何使用API來(lái)驗(yàn)證兩個(gè)bean屬性是否相等(例如驗(yàn)證密碼字段與密碼驗(yàn)證字段匹配)。在注釋中,我希望類(lèi)似于:public class MyBean {
@Size(min=6, max=50)
private String pass;
@Equals(property="pass")
private String passVerify;}
3 回答

縹緲止盈
TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
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貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
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; ...}
添加回答
舉報(bào)
0/150
提交
取消