Username Validator in Java

 Username Validatator

  Usernames should be formatted and they should conform to follow some validation constraints   as an example


Type                                           Constraints

Length of username                   Inclusive 6 to 26 characters 

Containing figures                      Only alphanumeric characters

first figure being                        An alphabetical character


These usernames can be validated inside in register / signup functionalities  of your web application.


Now user enters an username as a string in the registration form provided.


Then they fill out the rest of info like email , password  and confirm password etc and submits


After that you need to validate these user inputs.

To do this we have few options

1. Using javascript regex to validate  it before submitting the form (with using jquery, JS,or other  front end js library,

2.   Using model attributes in your "User"view model  class(with using[regular Expression] for ASP.net or Pattern for Spring)

3.  Using server -side code to match and validate the pattern (This enables us to check the availabality

uniqueness  within the user table)

A recommended  regex pattern (for java) given below checks if the String input follows validation constraints given above.

String userRegex ="[a-zA-Z][a-zA-Z0-9_]{5,25}";

.The tokens used in the regex are as below

^

This denotes the first character  of the String

[a-zA-Z]

All the alphabetical and non-numerical characters 

^[a-zA-Z]

The first character being a alphabetical character.

[a-zA-Z0-9_]

The rest of the string can be alphanumerical characters with no spaces.

(Alphabetical characters with mixed case integer numbers, underscore)

{5,25}

This denotes the length constraint. (The length of the string input should  be between 

6 and 26 inclusive.Since the first token of ^[a-zA-Z] if checked the length we checking reduced by one .

So we need to check if it ranges from 5 to 25 roe rest

*

This denotes the whole pattern will be checked

$


This denotes the end of the pattern 

The following Java Program matches if the given username is valid and conform to our ruleset.



public static void main(String[] args){

String userRegex ="^[a-zA-Z][a-zA-Z0-9_]{5,25}+$";

java.util.Scanner sc=new java.util.Scanner(System.in);
System.out.println("Enter username: ");
String userName=sc.nextLin();

if(userName.matches(userRegex)){
System.out.println("valid username");
}else{
System.out.orintln("Invalid username");
}
sc.close();

}






Comments

Blogs