Username Validation using Java as per Client’s Requirement

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

USERNAME VALIDATION USING JAVA

Consider an employer is assigned to validate the username policy in his/her company’s internal networking platform developed in 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 characters otherwise, it will consider as 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 is as given below:

  • For each of the usernames, the output will print the string Valid if the username is valid as per our specified requirements. Otherwise, it will print Invalid. The program will check for each username and print if it is valid or invalid in each line.

Let’s take a look at the Java code below:

//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
[email protected]
_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

Your email address will not be published.