Tuesday, March 21, 2023
HomeSoftware EngineeringLearn how to Validate Usernames with Regex in Java

Learn how to Validate Usernames with Regex in Java


The problem

Write a easy regex to validate a username. Allowed characters are:

  • lowercase letters,
  • numbers,
  • underscore

Size ought to be between 4 and 16 characters (each included).

The answer in Java code

Choice 1:

public class PasswordValidation {
  public static boolean validateUsr(String s) {
    return s.matches("[a-z_d]{4,16}");
  }
}

Choice 2:

import java.util.regex.Sample;
public class PasswordValidation {
  personal static remaining Sample usernamePattern = 
      Sample.compile("[a-z0-9_]{4,16}");
  public static boolean validateUsr(String s) {
    return usernamePattern.matcher(s).matches();
  }
}

Choice 3:

public class PasswordValidation {
  public static boolean validateUsr(String s) {
    return s.matches("[p{Ll}d_]{4,16}");
  }
}

Check circumstances to validate our answer

import org.junit.Check;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Check
    public void basicTests() {
        assertEquals(true, PasswordValidation.validateUsr("regex"));
        assertEquals(false, PasswordValidation.validateUsr("a"));
        assertEquals(false, PasswordValidation.validateUsr("Hass"));
        assertEquals(false, PasswordValidation.validateUsr("Hasd_12assssssasasasasasaasasasasas"));
        assertEquals(false, PasswordValidation.validateUsr(""));
        assertEquals(true, PasswordValidation.validateUsr("____"));
        assertEquals(false, PasswordValidation.validateUsr("012"));
        assertEquals(true, PasswordValidation.validateUsr("p1pp1"));
        assertEquals(false, PasswordValidation.validateUsr("asd43 34"));
        assertEquals(true, PasswordValidation.validateUsr("asd43_34"));
    }
    
    @Check
    public void randomTests() {
      for (int i=1; i<201;i++) {
        String testString = makeWord(0,20);
        assertEquals("Check №"+i+" with string => "+testString, sollution(testString), PasswordValidation.validateUsr(testString));
      }
    }
    
    personal boolean sollution(String str) {
      return str.matches("[a-z_d]{4,16}");
    }
    
    personal String makeWord(int min, int max) {
      StringBuilder sb = new StringBuilder();
      String potential = "abcdefghijklmnopqrstuvwxyz_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_ 0123456789";
      int size = (int)Math.ceil((Math.random() * max) + min);
    
      for(int i = 0; i < size; i++) {
          sb.append(potential.charAt((int)Math.flooring(Math.random() * potential.size())));
      }
    
      return sb.toString();
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments