#Pattern validation on a blank field - java

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.

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.

It seems that the problem is that the #Size restriction does not allow form submission even after making the whole regex pattern optional.
The workaround I suggest is moving the size restriction into the regex pattern:
regexp = "^(?:(?=.{6,20}$)[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+‌​‌​)*(\\.[A-Za-z‌​]{2,}))?$"
Where the outer (?:...)? encloses your pattern making it possible to match an empty string, and (?=.{6,20}$) is a positive lookahead that - before matching the pattern - checks if there are 6 to 20 characters in the text. If there are fewer or more, the match is failed.
The only disadvantage is that you can only display one error message with it.

Related

Handle validation for non numeric characters getting passed to Integer variable

Is there an annotation that could be used to prevent the following error from getting thrown by my Java application if I send a non numerical value for year in my GET request?
I currently have this:
#NotNull
#Digits(integer = 4, fraction = 0, message = "Provide valid Year in the format YYYY")
#Min(value = 1900, message = "Year must be greater than 1900")
private Integer year;
When I pass a value with letters I get a NumberFormatException before #Digits and #Min is executed. I also tried #Pattern with a regex value but that caused a 500 error.
"Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'yearOfReg'; nested exception is java.lang.NumberFormatException: For input string: \"20c15\"
The answer is very short: no. That's because the validation is configured for the Integer year field. That means that the field must get populated before it can be validated. That population fails if you submit a value that cannot be parsed to an Integer.
The best way to handle this case is to add error handling for the mapping exception. For Jackson that's a MismatchedInputException.
An alternative is to change the field to a String. That allows you to use #Pattern, but you will need to convert yourself. That can be done in the class itself using a getter.

How do I add regex to #Pattern annotation to match one of two specific strings or a null?

I've added #Pattern annotation to a query parameter in my rest controller (SpringBoot Kotlin). I would like the regex in the pattern to accept -
optionA or optionB or null (nothing/an empty string)
The following works, but of course does not include the empty option -
#Pattern(regexp = "(?i)optionA||(?i)optionB")
This does not work -
#Pattern(regexp = "(?i)optionA||(?i)optionB||^\\s*\$")
Can anybody help me with this? :)
Thanks!
Inside the #Pattern annotation, the pattern is used to match the entire string, so you can use
#Pattern(regexp = "(?i)(?:optionA)?")
which is actually \A(?i)(?:optionA)?\z:
\A - start of string (implicit here)
(?i) - case insensitive embedded flag option
(?:optionA)? - an optional non-capturing group that matches optionA or empty string
\z - end of string (implicit here).
The null is a memory address, not a string, it cannot be matched with regex, as regex only deals with strings.
I tryed this optionA|optionB|^\s$ on https://regex101.com/ and worked well. Could you try on your app to check?

REST parameter validation

Is there a way to specifically mention the length for the request parameter? My Parameter could be of length 4 or 6 ..
But specifying like below :
#Size(min=4, max=6)
#RequestParam String param1
Would allow length 5 too which is invalid in my case ? Is there a way to accomplish this without a customer validator?
Thanks
You could try to use #Pattern annotation which verifies that string follows specific regexp.
Then, you need to build regexp that will be something like this - ^(?=[0-9]*$)(?:.{4}|.{6})$ (checks that string contains only 4 digits or 6 digits).
Pattern annotation docs

Spring data MongoDB check if field contains text

I have field in mongoDb collection "name" which contains:
"26.11.2018(2)"
I use regex expression for searching if any string contains in field "name":
String search = "11.2018(2)";
return Criteria.where("name").regex(search);
I got exception, that regular expression is wrong(because of ")"). Is there any other possibility for searching like this?
You need to escape the value that's used in the regex.
I can't test it now, but it's possible that it may work:
String search = "some pattern(a)12.";
pattern = Pattern.compile(Pattern.quote(search), Pattern.CASE_INSENSITIVE);
return Criteria.where("name").regex(pattern);
https://mongodb.github.io/mongo-java-driver/3.4/javadoc/?com/mongodb/client/model/Filters.html

Restrict particular domain in email regular expression

I have an existing regex which validates the email input field.
[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!$%&'*+/=?^_`{|}~-]+)*(\\.)?#(?:[a-zA-Z0-9ÄÖÜäöü](?:[a-zA-Z0-9-_ÄÖÜäöü]*[a-zA-Z0-9_ÄÖÜäöü])?\\.)+[a-zA-Z]{2,}
Now, I want this regex to not match for two particular type of email IDs. Which are wt.com and des.net
To do that I made the following changes in the above expression like this.
[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!$%&'*+/=?^_`{|}~-]+)*(\\.)?#(?!wt\\.com)(?!des\\.net)(?:[a-zA-Z0-9ÄÖÜäöü](?:[a-zA-Z0-9-_ÄÖÜäöü]*[a-zA-Z0-9_ÄÖÜäöü])?\\.)+[a-zA-Z]{2,}
After this it does not matches with any email id which ends with the wt.com and des.net which is right.
But the problem is it does not match with wt.comm or any other letter after the restricted string too..
I just want to restrict email which ends with wt.com and des.net
How do I do that?
Below is the sample emails which should match or not.
ajcom#wt.com : no match
ajcom#aa.an : match
ajcom#wt.coms :match
ajcom#des.net : no match
ajcom#des.neta: match
If you want to prevent only wt.com and des.net which have no characters after it you can add $ anchor (which represents end of string) at the end of each negative-look-ahead.
So instead of (?!wt\\.com)(?!des\\.net) use (?!wt\\.com$)(?!des\\.net$)

Categories

Resources