Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross field validation (JSR 303) problem

I have a simple bean, i.e.:

public class MyBean {

  private boolean selected;

  private String someString;

  ...
}

So if selected is true, I want someString to be @NotNull etc. .

Any hints, links how to achieve this behaviour?

Thanks Jonny

like image 342
user871611 Avatar asked Mar 05 '26 17:03

user871611


1 Answers

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

And there’s example for your case:

@SpELAssert(value = "someString != null", applyIf = "selected",
            message = "{validator.missing_some_string}")
public class MyBean {

    private boolean selected;

    private String someString;

  ...
}

Actually this was too easy. Try something more interesting, maybe an equality of password fields when one of them is not null.

@SpELAssert(value = "password.equals(passwordVerify)",
            applyIf = "password || passwordVerify",
            message = "{validator.passwords_not_same}")
public class User {

    private String password;
    private String passwordVerify;
}

And you can even use your own “helper methods” in these expressions!

Compared to Hibernate Validator’s @ScriptAssert annotation, this is pure Java solution, it’s not using any JSR-223 compliant scripting language which may be a little problematic. On the other side, this solution is interesting only for Spring-based applications.

like image 95
Jakub Jirutka Avatar answered Mar 07 '26 05:03

Jakub Jirutka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!