Username Validation Java - java

I'm new in Java, so I don't know very good the language.
I have a simple HTML Form to fill register for Login.
My problem is a detail in the username, it can't have some invalid character (accents and symbols, for example) and I don´t know how to check the username characters.
I used request.getParameter("username") to get username in a String variable.
String username = request.getParameter("username");
How can I proceed?

A simple way is the String#matches(String regex) function:
boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
String username = request.getParameter("username");
boolean valid = (username != null) && username.matches("[A-Za-z0-9_]+");
but if this is to be used multiple times is more efficient to use a Pattern:
Pattern pattern = Pattern.compile("[A-Za-z0-9_]+");
and use it each time:
boolean valid = (username != null) && pattern.matcher(username).matches();

Use this Bean Validation library:
https://github.com/ankurpathak/username-validation
https://mvnrepository.com/artifact/com.github.ankurpathak.username/username-validation
It has all constraints for google like username validation and many more.
Library has different constraint to deal with username validation:
UsernamePattern to allow a-z,0-9,period and underscore characters. These characters can we turned off with some flags in constraints like includePeriod, includeUnderscore and useDigit
EndWithAlphabet to check if username end with alphabet
StartWithAlphabet to check if username start with alphabet
StartWithAlphaNumeric to check username start with alphanumeric
EndWithAlphaNumeric to check username end with alphanumeric
NotContainConsecutivePeriod to check username not contain consecutive period
NotContainConsecutiveUnderscore to check username not contain consecutive underscore
NotContainPeriodFollowedByUnderscore to check username not contain period followed by underscore
NotContainUnderscoreFollowedByPeriod to check username not contain underscore followed by period
All the constraints by default ignore blank so that it will be reposted separately by NotBlank standard bean validation constraint and same can we turned of using ignoreBlank(true by default) flag of each constraint. So google like username can be achieved by:
#UsernamePattern
#StartWithAlphaNumeric
#NotContainConsecutivePeriod
#EndWithAlphaNumeric
#NotBlank
private String username;

Related

Codename one create a PIN constraint

Am creating a form with some Text inputs where a user can update their PIN, so i need the inputs to be only numeric and also kind a password- masked.
I've tried this here but it only makes the input masked and accepts even characters,
TextComponent currentPIN = new TextComponent().labelAndHint("Current Pin").constraint(TextArea.NUMERIC).constraint(TextArea.PASSWORD);
TextComponent newPIN = new TextComponent().labelAndHint("New PIN").constraint(TextArea.NUMERIC).constraint(TextArea.PASSWORD);
TextComponent confirmPIN = new TextComponent().labelAndHint("Confirm PIN").constraint(TextArea.NUMERIC).constraint(TextArea.PASSWORD);
how can I achieve this, I want the input to accept only PIN, that's numeric and be masked.
You cannot chain calls to constraint() that way and have them add up.
From the Javadoc (my emphasis):
public void setConstraint(int constraint)
Sets the constraint which provides a hint to the virtual keyboard input, notice this doesn't limit input type in any way!
Parameters:
constraint - one of ANY, EMAILADDR, NUMERIC, PHONENUMBER, URL, DECIMAL it can be bitwised or'd with one of PASSWORD, UNEDITABLE, SENSITIVE, NON_PREDICTIVE, INITIAL_CAPS_SENTENCE, INITIAL_CAPS_WORD. E.g. ANY | PASSWORD.
The proper form is
...constraint(TextArea.NUMERIC | TextArea.PASSWORD)

java.util.regex.PatternSyntaxException: Illegal repetition near index 12

I am new to regEx. I need to validate email using java. I have created regEx for email validation by hardcoding the domain name. But the domain name should be dynamic. I have passed the domain name as a parameter. But I don't know how to pass parameter in regEx.
But I tried this code, then I got the error "java.util.regex.PatternSyntaxException: Illegal repetition near index 12". I have followed some answers but it doesn't help for me. From those answers I understood about repetition quantifier. Can you tell me what I am missing here and how to solve this issue?
public static boolean validateEmail(String email, String domainName) {
pattern = Pattern.compile("^([\\w-\\.]+)# {"+ domainName +"}" , Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(email);
return matcher.matches();
}
{ and } have meaning in regex, namely for specifying how often the character before it can repeat. E.g. a{5} matches aaaaa.
If you want to use curly braces in regex, you should escape them like \\{ and \\}.
But that's not what you need for passing this as a parameter — it will just be literal text at that point. If you want to only match that literal domain, you could do Pattern.compile("^([\\w-\\.]+)#" + domainName, Pattern.CASE_INSENSITIVE).

String validation based on criteria

I have a requirement where I need to validate a string:
String input1 = example#gmail.com , example1#gmail.com;
String input2 = example#yahoo.com , example1#gmail.com;
String input 1 == valid ::: Valid because all email ids are of same domain
String input 2 == invalid
You can build the logic in the following way.
String input1 = example#gmail.com , example1#gmail.com , example1#gmail.com;
Follow the steps.
Split the entire string using comma (,). You will get an array of email ids.
From the above array of email id, separate out the domain by stripping from # symbol and put in a HashSet. It means the HashSet should contain all the domains.
If the HashSet size is 1 finally or at the end it means that input1 has same doamins, as per your requirement it is valid.
If the HashSet contains more than 1, as per your requirement it is invalid.
This is a simple logic, However there may be better logic to solve it.

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$)

#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.
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.

Categories

Resources