Reputation: 3595
I am working on a spring boot application and I have a password reset form. I am using a class like this to validate the inputs.
public class PasswordResetForm {
@NotEmpty
@Size(min=6, message="must be at least 6 characters")
private String password;
private String passwordConfirm;
//Getter and Setters
}
So, I now want to validate if the fields passwordConfirm and password are equals, I searched all over but could not find how to add a custom validation in this case. So, how do I add custom validation for other fields?
My controller's action looks like this
@RequestMapping(value = "/password-change/{id}-{tokenNumber}", method = RequestMethod.POST)
public String changePassword(@PathVariable String id, @PathVariable String tokenNumber, @Valid PasswordResetForm form, BindingResult formBinding, Model model) {
if (formBinding.hasErrors())
return "change-password";
//Other stuff
}
Upvotes: 1
Views: 5483
Reputation: 1059
or if you wanna validate simply only this (passwordConfirm and password are equals) case.
you can use @AssertTrue.
@AssertTrue
public boolean isDifferentPass() {
return !password.equals(passwordConfirm);
}
if these two fileds are same , then your controller's BindingResult has error
Upvotes: 5
Reputation: 957
You can use @Validated annotation for forcing validation of @RequestParam and @PathVariable. @Valid is for forcing validation of @RequestBody
Upvotes: 0
Reputation: 7868
For your needs, you could consider creating a custom @Constraint. You would first create the constraint annotation:
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=MyConstraintValidator.class)
public @interface MyConstraint {
}
And then the constraint validator:
import javax.validation.ConstraintValidator;
public class MyConstraintValidator implements ConstraintValidator {
@Autowired;
private Foo aDependency;
...
}
You can find additional reference for this here: Dependency Injection in JSR-303 Constraint Validator with Spring fails
And on the Spring Docs:
http://docs.spring.io/autorepo/docs/spring/3.2.x/spring-framework-reference/html/validation.html
Upvotes: 4