Tuesday, April 23, 2024
HomeSoftware EngineeringMethods to Validate Usernames with Regex in Java

Methods 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 needs to be between 4 and 16 characters (each included).

The answer in Java code

Possibility 1:

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

Possibility 2:

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

Possibility 3:

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

Take a look at instances to validate our answer

import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Take a look at
    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"));
    }
    
    @Take a look at
    public void randomTests() {
      for (int i=1; i<201;i++) {
        String testString = makeWord(0,20);
        assertEquals("Take a look at №"+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 doable = "abcdefghijklmnopqrstuvwxyz_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_ 0123456789";
      int size = (int)Math.ceil((Math.random() * max) + min);
    
      for(int i = 0; i < size; i++) {
          sb.append(doable.charAt((int)Math.ground(Math.random() * doable.size())));
      }
    
      return sb.toString();
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments