Skip to content
Advertisement

Java Regex First Name Validation

I understand that validating the first name field is highly controversial due to the fact that there are so many different possibilities. However, I am just learning regex and in an effort to help grasp the concept, I have designed some simple validations to create just try to make sure I am able to make the code do exactly what I want it to, despite whether or not it conforms to best business logic practices.

I am trying to validate a few things.

  1. The first name is between 1 and 25 characters.
  2. The first name can only start with an a-z (ignore case) character.
  3. After that the first name can contain a-z (ignore case) and [ ‘-,.].
  4. The first name can only end with an a-z (ignore case) character.

    public static boolean firstNameValidation(String name){
    
        valid = name.matches("(?i)(^[a-z]+)[a-z .,-]((?! .,-)$){1,25}$");
    
        System.out.println("Name: " + name + "nValid: " + valid);
    
        return valid;
     }
    

Advertisement

Answer

Your expression is almost correct. The following is a modification that satisfies all of the conditions:

valid = name.matches("(?i)(^[a-z])((?![ .,'-]$)[a-z .,'-]){0,24}$");
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement