Cross field validation with Hibernate Validator (JSR 303)

前端 未结 15 1768
渐次进展
渐次进展 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:04

    I don't have the reputation for commenting on the first answer but wanted to add that I have added unit tests for the winning answer and have the following observations:

    • If you get the first or field names wrong then you get a validation error as though the values don't match. Don't get tripped up by spelling mistakes e.g.

    @FieldMatch(first="invalidFieldName1", second="validFieldName2")

    • The validator will accept equivalent data types i.e. these will all pass with FieldMatch:

    private String stringField = "1";

    private Integer integerField = new Integer(1)

    private int intField = 1;

    • If the fields are of an object type which does not implement equals, the validation will fail.

提交回复
热议问题