jack
jack

Reputation: 1942

hibernate validator: validate 2 fields match

I was wondering, am I overlooking something or does the hibernate validator offer no annotation to verify that 2 fields are equal (such as a password). I know I can write my own validators, but well this seems like standard functionality.

Upvotes: 0

Views: 4479

Answers (4)

Jakub Jirutka
Jakub Jirutka

Reputation: 10817

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.

This will validate equality of password fields when at least one of them is not empty.

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

    private String password;
    private String passwordVerify;
}

Upvotes: 4

jack
jack

Reputation: 1942

Just went for the custom validator route. The other 2 answers here aren't really related to the question. With a bit of googling I found a fieldmatch example.

Upvotes: 0

Heiko Hatzfeld
Heiko Hatzfeld

Reputation: 3197

Hibernate is a ORM Mapper.

It is used to persist data into a DB and extract it again. As such, having 2 fields with an identical value makes not much sense (From a persistance point of view). Thats something you should check in your Business logic.

And I am with Junesh... Dont persist your passwords in a retrievable format... Look up Hasing and Salting - Or even better, think about openID so you dont have to bother your clients with yet another stupid password...

Upvotes: -1

Jinesh Parekh
Jinesh Parekh

Reputation: 2141

I am hoping you are not saving the confirm password in the database as well. You do not have any out of the box validations for this, but instead you will have to use custom annotation which is pretty straight forward as well.

Upvotes: -2

Related Questions