Thursday, 21 December 2017

How to write a regex to validate the username | Java Regex | Regex in java


Click here to watch on Youtube :
https://www.youtube.com/watch?v=xYCbzomotRk&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge

How to write a regex to validate the username | Java Regex | Regex in java
UserNameValidator.java

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 *
 * How to validate username with regular expression
 *
 */

public class UserNameValidator
{
    private Pattern pattern;
    private Matcher matcher;

    private static final String USERNAME_REGEX = "^[a-z0-9_-]{3,15}$";

    public UserNameValidator()
    {
        pattern = Pattern.compile(USERNAME_REGEX);
    }

    /*
     * Validate username with regular expression
     *
     * @param username username for validation
     *
     * @return true valid username, false invalid username
     */

    public boolean validate(final String username)
    {

        matcher = pattern.matcher(username);
        return matcher.matches();

    }

}

RegexDemo.java

/**
 *
 * How to validate username with regular expression
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        UserNameValidator unValidator = new UserNameValidator();
       
        System.out.println("'peter34' is valid userName? = "+unValidator.validate("peter34"));
        System.out.println("'peter_34' is valid userName? = "+unValidator.validate("peter_34"));
        System.out.println("'peter-34' is valid userName? = "+unValidator.validate("peter-34"));

        System.out.println();

        /*
         * too short, min 3 characters
         */

        System.out.println("'pk' is valid userName? = "+unValidator.validate("pk"));
        /*
         * “@" character is not allow
         */

        System.out.println("'peter@89' is valid userName? = "+unValidator.validate("peter@89"));

        /*
         * too long, max characters of 15
         */

        System.out.println("'peter11111323445' is valid userName? = "+unValidator.validate("peter11111323445"));
    }

}

Output

'peter34' is valid userName? = true
'peter_34' is valid userName? = true
'peter-34' is valid userName? = true

'pk' is valid userName? = false
'peter@89' is valid userName? = false
'peter11111323445' is valid userName? = false

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/RegexDemo_username.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/RegexDemo_username

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/576579fab6c376d5ecd7cb5b7402b7fd1a7c4ae3/BasicJava/RegexDemo_username/?at=master

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment