Thursday, December 3, 2020

How to validate a username with the aid of regular expressions in Java?

 I find regular expressions interesting because if you got the right idea of when and how to use them, it will help you to reduce lines of code and would save time as well. 

In the below example, I am going to demonstrate on how to validate a simple username (assume username entered in a System during the Sign Up process) .

Rules

  • The username consists of 8 to 30 characters inclusive. If the username consists of less than 8 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 character [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]

I am going to use the stdin to get inputs and stdout to print the results. The first input will indicate how many input strings (usernames) are going to be validated and subsequent inputs will indicate each username to be validated.

import java.util.Scanner;

class Validator {
public static final String regularExpression = "^[a-zA-Z][a-zA-Z0-9|_]{7,29}$";
}

public class UsernameValidator{
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
int numOfUserNames = Integer.parseInt(scanner.nextLine());

while(numOfUserNames > 0){

String userName = scanner.nextLine();

if(userName.matches(Validator.regularExpression)){
System.out.println("Valid Username");
}else{
System.out.println("Invalid Username");
}
numOfUserNames--;
}
}
}

Input / Output:


5
Amanda
Invalid Username
Cassandra
Valid Username
Amelia_2134
Valid Username
1Jessica231
Invalid Username
Emma_654424
Valid Username

Explanation to the regular expression I used above

^ [a-zA-Z] --> indicates the beginning of the string which should contain a-z or A-Z (only alphabets)
[a-zA-Z-0-9_] --> indicates the string starting from the second character of the username which can consists of alphabets, digits or _. No Symbols allowed here. 
{7,29}  --> indicates the length of the username starting from the second character. which is 7 to 29 character long.

A great approach to practice regular expressions is to create your own simple java programs and imagine various types of validations that could perform in a System, and crack them with the aid of Regular expressions instead of using String manipulations or conditional blocks to resolve the challenges.




No comments:

Post a Comment