Validate UserName Using Regular Expression In Java

Chapter: Regular Expression Last Updated: 22-09-2018 08:14:56 UTC

Program:

            /* ............... START ............... */
                
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaValidateUserName {
	private static Pattern userNamePattern = Pattern.compile("^[a-z0-9_-]{6,14}$");

	public static boolean validateUserName(String userName) {

		Matcher mtch = userNamePattern.matcher(userName);
		if (mtch.matches()) {
			return true;
		}
		return false;
	}

	public static void main(String a[]) {
		System.out.println("Is 'javascan' a valid user name? " + validateUserName("javascan"));
		System.out.println("Is 'scan' a valid user name? " + validateUserName("scan"));
		System.out.println("Is 'JAVASCAN' a valid user name? " + validateUserName("JAVASCAN"));
		System.out.println("Is 'javascan90' a valid user name? " + validateUserName("javascan90"));
		System.out.println("Is 'java_4_scan' a valid user name? " + validateUserName("java_4_scan"));
	}
}
                /* ............... END ............... */
        

Output

Is 'javascan' a valid user name? true
Is 'scan' a valid user name? false
Is 'JAVASCAN' a valid user name? false
Is 'javascan90' a valid user name? true
Is 'java_4_scan' a valid user name? true

Notes:

  • If you want to support uppercase characters then regular expression should be ^[a-zA-Z0-9_-]{6,14}$.

Tags

Validate UserName,Regular Expression, Java,name validation in java using regular expression, user validation in java, how to check username validation in java, validation for username.

Similar Programs Chapter Last Updated
Java Regular Expression Match Single Digit Regular Expression 15-12-2016
Java Regular Expression To Check Number With Dot Separator And Two Decimal Regular Expression 14-12-2016
Java Regular Expression To Check Numeric Regular Expression 14-12-2016
Java Regular Expression Digit Only Regular Expression 14-12-2016
Java Check Date Format Example Regular Expression 14-09-2016
Java Validate email Address Regular Expression 13-09-2016
Java Replace All Occourances Of String Example Regular Expression 13-09-2016
Java Make First Letter Of Each Word In Uppercase Regular Expression 13-09-2016
Java Match Phone Numbers Using Regular Expression Regular Expression 11-09-2016
Java Last Index Of Word Using Regular Expression Regular Expression 11-09-2016
Java Find Word Occurrence Using Regular Expression Regular Expression 11-09-2016
Java Splitting String Using Regular Expression Regular Expression 11-09-2016
Java Regex Pattern Split Example Regular Expression 21-06-2016
IP Address From String In Java Regex Regular Expression 21-07-2016
Java Regex IP Address Example Regular Expression 21-07-2016
Regular Expression In Java Example Regular Expression 09-07-2016
Pattern Matching In Java Example Regular Expression 09-07-2016

1