Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @Pattern on non-mandatory fields JSR 303

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.

like image 790
Erhan Bagdemir Avatar asked May 14 '11 00:05

Erhan Bagdemir


People also ask

How do you validate fields in Spring Boot?

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.

How do you set a Spring Boot mandatory field?

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.

Which annotation is used for validation?

The @Valid annotation applies validation rules on the provided object. The BindingResult interface contains the result of validation.

How do you validate a condition in Java?

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.


1 Answers

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.

like image 62
BalusC Avatar answered Sep 26 '22 08:09

BalusC