Cross field validation with Hibernate Validator (JSR 303)

前端 未结 15 1948
渐次进展
渐次进展 2020-11-22 02:37

Is there an implementation of (or third-party implementation for) cross field validation in Hibernate Validator 4.x? If not, what is the cleanest way to implement a cross fi

15条回答
  •  无人共我
    2020-11-22 03:02

    If you’re using the Spring Framework then you can use the Spring Expression Language (SpEL) for that. I’ve wrote a small library that provides JSR-303 validator based on SpEL – it makes cross-field validations a breeze! Take a look at https://github.com/jirutka/validator-spring.

    This will validate length and equality of the password fields.

    @SpELAssert(value = "pass.equals(passVerify)",
                message = "{validator.passwords_not_same}")
    public class MyBean {
    
        @Size(min = 6, max = 50)
        private String pass;
    
        private String passVerify;
    }
    

    You can also easily modify this to validate the password fields only when not both empty.

    @SpELAssert(value = "pass.equals(passVerify)",
                applyIf = "pass || passVerify",
                message = "{validator.passwords_not_same}")
    public class MyBean {
    
        @Size(min = 6, max = 50)
        private String pass;
    
        private String passVerify;
    }
    

提交回复
热议问题