How to validate a Username using Regular Expressions in Java
Last Updated :
16 Oct, 2020
Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions.
A username is considered valid if all the following constraints are satisfied:
- The username consists of 6 to 30 characters inclusive. If the username
consists of less than 6 or greater than 30 characters, then it is an invalid username.
- The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters [a – z], uppercase characters [A – Z], and digits [0 – 9].
- The first character of the username must be an alphabetic character, i.e., either lowercase character
[a – z] or uppercase character [A – Z].
Examples:
Input: str = “1Geeksforgeeks”
Output: False
Explanation:
The given username is invalid because it starts with a digit.
Input: str = “Geeksforgeeks_21”
Output: True
Explanation:
The given username satisfies all the conditions mentioned.
Input: str = “Geeksforgeeks?10_2A”
Output: False
Explanation:
The given username is invalid because it consists of invalid character “?”.
Approach: The idea is to use Regular Expressions to validate if the given username is valid or not. The following steps can be followed to compute the answer:
- Get the string.
- Form a regular expression to validate the given string. According to the conditions, the regular expression can be formed in the following way:
regex = "^[A-Za-z]\\w{5, 29}$"
Where:
- “^” represents that starting character of the string.
- “[A-Za-z]” makes sure that the starting character is in the lowercase or uppercase alphabet.
- “\\w{5, 29}” represents a check to make sure that the remaining items are word items, which includes the underscore, until it reaches the end and that is represented with $.
- The “{5, 29}” represents the 6-30 character constraint given to us minus the predefined first character.
- Match the string with the Regex. In Java, this can be done using Pattern.matcher().
- Return true if the string matches with the given regex, else return false.
Below is the implementation of the above approach:
import java.util.regex.*;
class GFG {
public static boolean isValidUsername(String name)
{
String regex = "^[A-Za-z]\\w{5,29}$" ;
Pattern p = Pattern.compile(regex);
if (name == null ) {
return false ;
}
Matcher m = p.matcher(name);
return m.matches();
}
public static void main(String[] args)
{
String str1 = "Geeksforgeeks" ;
System.out.println(isValidUsername(str1));
String str3 = "1Geeksforgeeks" ;
System.out.println(isValidUsername(str3));
String str5 = "Ge" ;
System.out.println(isValidUsername(str5));
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...