How to validate Username using Java Regular Expression

In this tutorial we are going to see about how to validate Username using Java Regular Expression

User Name Regular Expression Pattern

^[a-z0-9]{5,15}$

UserNameValidator.java

package com.ehowtonow.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserNameValidator {
 private static final String PATTERN = "^[a-z0-9]{5,15}$";

 public static void main(String[] args) {

  System.out.println("Validate jtc123 : "+validate("jtc123"));
  System.out.println("Validate JTC123 : "+validate("JTC123"));
  System.out.println("Validate Jtc45 : "+validate("Jtc45"));
  System.out.println("Validate 123Jtc : "+validate("123Jtc"));
  System.out.println("Validate jtc : "+validate("jtc"));
  System.out.println("Validate jtcjtc : "+validate("jtcjtc"));
  System.out.println("Validate 123jtc : "+validate("123jtc"));

 }

 private static boolean validate(String userName) {
  Pattern pattern = Pattern.compile(PATTERN);
  Matcher matcher = pattern.matcher(userName);
  return matcher.matches();

 }

}

Output :

Validate jtc123 : true
Validate JTC123 : false
Validate Jtc45 : false
Validate 123Jtc : false
Validate jtc : false
Validate jtcjtc : true
Validate 123jtc : true


Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. How to validate IPv4 Address using Java Regular Expression
  2. How to validate password using Java Regular Expression
  3. How to replace all occurrences of a string using RegEx
  4. How to validate Username using Java Regular Expression
  5. Java RegEx to validate Date – dd/mm/yyyy pattern
  6. How to validate MAC Address using Java Regular Expression
  7. How to validate IPv4 Address with Port using Java Regular Expression
  8. How to validate Email Address using Java Regular Expression

Be the first to comment

Leave a Reply