How can i use @Pattern
constraint on non-mandatory form fields ?
@Pattern(regexp="...")
private String something;
as soon as i submit my form, i get validation error as expected but the user may leave the field empty, since this is not a mandatory field.
PS: i could write my own constraint annotation. However, i just ask an easier way combining annotations or adding annotation attributes. JSR303 implementation is hibernate-validator.
Validation in Spring Boot is done mainly by using Hibernate Validator — an implementation of Java Bean Validation using annotation based constraints. But while Hibernate provides a powerful set of constraint violations checkers out of the box, we'll need to put some effort into handling the exceptions it throws.
You can use groups parameter in JSR303 annotations. For above example Json body {"id": 1} will work for POST but for PUT you will get HTTP 400 telling you that "content parameter must not be empty". {"id": 1, "content":"World"} will be accepted for both methods. Irek L.
The @Valid annotation applies validation rules on the provided object. The BindingResult interface contains the result of validation.
The isValid() method contains the concrete validation logic. Using apache's BeanUtils library we extract the value of the conditional property from our partner object. Then, in doConditionalValidation() method we check if that concrete value is contained in the values array from our annotation.
Just set it with null
instead of empty string. Since empty HTML input fields are by default submitted as an empty string as HTTP request parameter, you need to let your MVC framework interpret empty submitted values as null
. This is in JSF easy done by a <context-param>
in web.xml
. However, since you're using Spring MVC and I don't do it, I searched a bit here and found this answer which may be of use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With