Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate only if the field is not Null

I use JSR303 Spring Validation and I have the following;

@Digits(fraction = 0, integer = 15)
private String tpMobile;

Validation says Must be number between 10-15 digits, but the thing is this field is optional. So when user left it empty also the same error message shows.

So what I want to do is validate only if the field is not empty. If the field is empty skip validating that field

like image 954
Ravindu Avatar asked Oct 09 '13 04:10

Ravindu


2 Answers

Instead of using @Digit, I would like to suggest you to use @Pattern(message="YOUR_MESSAGE", regexp="REGULAR_EXPRESSION")

Main reason is that we show message for such set of values for which we want to restrict the user, here in your condition message is displayed for that value which you don't want to restrict.

So You wants to restrict user to enter anything other than blank space and numbers.Make a regular expression for that and use @Pattern with that.

For your case :

@Pattern(message="YOUR_MESSAGE", regexp="^(\\s*|\\d{10,15})$")
like image 190
Satyam Koyani Avatar answered Oct 15 '22 00:10

Satyam Koyani


Obviously, you form submits empty strings instead of nulls. Just check the value of tpMobile

like image 20
Gregory Klimov Avatar answered Oct 15 '22 00:10

Gregory Klimov