Username Validation using Java as per Client’s Requirement

In this Java post, we will learn how to validate username in Java. For making it easy we have provided an easy example of username validation using Java.

USERNAME VALIDATION USING JAVA

In this problem, an employer is assigned to validate the username policy in his/her company’s internal networking platform using java. According to that policy, a username is considered valid only if all the following constraints are satisfied:

  • The username length must range between 7 to 20 otherwise, it’s an invalid username.
  • The username is allowed to contain only underscores ( _ ) other than alphanumeric characters.
  • The first character of the username must be an alphabetic character, i.e., [a-z] or [A-Z].

For example:

     UsernameValidity
  AlexaInvalid
  PriyamSurValid
  Alexa_7878Valid
  1PriyamSurInvalid
  Priyam?Sur()Invalid

The format of Input:

  • First input line: n, describing the total number of usernames.
  • Next n lines: string describing the username.

Constraints of Input:

  • 1<=n<=100
  • The username consists of printable characters.

So, The format of Output:

  • For each of the usernames, the output is “Valid” if the username is valid. Otherwise, print “Invalid” each on a new line.

Let’s take a look at the code:

//Java8

import java.util.Scanner;
class UsernameValidator {
    public static final String regularExpression = "^[a-zA-Z][a-zA-Z0-9_]{6,19}$";
}
public class Solution {
    private static final Scanner scan = new Scanner(System.in);
    
    public static void main(String[] args) {
        int n = Integer.parseInt(scan.nextLine());
        while (n-- != 0) {
            String userName = scan.nextLine();

            if (userName.matches(UsernameValidator.regularExpression)) {
                System.out.println("Valid");
            } else {
                System.out.println("Invalid");
            }           
        }
    }
}

Input:

8
Alexa
Tamanna
Samantha_21
2Priyam
Sukanyam?10_2A
JuliaZ007
Anjelina@007
_James007

Output:

Invalid
Valid
Valid
Invalid
Invalid
Valid
Invalid
Invalid

Hope, you enjoyed this tutorial and it helped you to solve your problem.

you can also read:

Leave a Reply