Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Pattern validation on a blank field

I am using validation annotations to validate the Email field, Here the email field is not mandatory, Still when I click on submit, It is validating and throwing error message when the field is empty,

Here are the annotations:

@Pattern(regexp = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$", 
            message = "registration.label.useremailformat.invalidformat")
@Size(min = 6, max = 20, message = "registration.label.useremail.length")
@SafeHtml
private String userEmailId;

How can I skip @Pattern validation when the email field is empty and validate only when the value is given? Any help would be highly appreciated.

like image 779
Thej Avatar asked Oct 23 '25 03:10

Thej


1 Answers

Modify your regexp to allow empty string and remove @Size:

@Pattern("^$|(<<old regexp>>)")
@SafeHtml
private String userEmailId;

... where <<old regex>> is a placeholder for your current lengthy regexp.

like image 146
Per Huss Avatar answered Oct 24 '25 16:10

Per Huss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!