How to validate a Username using Regular Expressions in Java

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:

  1. Get the string.
  2. 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.
  3. Match the string with the Regex. In Java, this can be done using Pattern.matcher().
  4. Return true if the string matches with the given regex, else return false.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to validate a username
// using Regular Expression or ReGex
  
import java.util.regex.*;
  
class GFG {
  
    // Function to validate the username
    public static boolean isValidUsername(String name)
    {
  
        // Regex to check valid username.
        String regex = "^[A-Za-z]\\w{5,29}$";
  
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
  
        // If the username is empty
        // return false
        if (name == null) {
            return false;
        }
  
        // Pattern class contains matcher() method
        // to find matching between given username
        // and regular expression.
        Matcher m = p.matcher(name);
  
        // Return if the username
        // matched the ReGex
        return m.matches();
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        // Test Case: 1
        String str1 = "Geeksforgeeks";
        System.out.println(isValidUsername(str1));
  
        // Test Case: 2
        String str3 = "1Geeksforgeeks";
        System.out.println(isValidUsername(str3));
  
        // Test Case: 3
        String str5 = "Ge";
        System.out.println(isValidUsername(str5));
    }
}

chevron_right


Output:

true
false
false

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

External Technical Content Reviewer at GeeksforGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : rajputbalram

Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.