1

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;
     }
    
3
  • 1
    Poor Günther :( Commented Sep 20, 2017 at 16:08
  • 1
    And what's your question? Commented Sep 20, 2017 at 16:09
  • (?<=[^a-z ',.-]|^)[a-z](?:(?:[a-z]|[ ',.-](?![ ',.-])){1,23}[a-z])?(?=[^a-z ',.-]|$). This will ensure that there is a non-name character or no character before the name (beginning of string), that the name consists of at least 1 alphabetic character, potentially followed by 1-23 of characters in the set a-z ',.- without two ' ,.- characters following each other and then followed by an alphabetic character, followed by a non-name character or no character (end of string). Also, use the i modifier for case-insensitivity Commented Sep 20, 2017 at 17:09

6 Answers 6

1

Try this regex

^[^- '](?=(?![A-Z]?[A-Z]))(?=(?![a-z]+[A-Z]))(?=(?!.*[A-Z][A-Z]))(?=(?!.*[- '][- '.]))(?=(?!.*[.][-'.]))[A-Za-z- '.]{2,}$

Demo

Edited Oct 13, 2024

My latest solution for int names:

^(?=([A-ZÀ-ÝŐŰẞŒ]|([a-zß-ÿőűœ][ '])))(?=(?![a-zß-ÿőűœ]+[A-ZÀ-ÝŐŰẞŒ]))(?=(?!.*[A-ZÀ-ÝŐŰẞŒ][A-ZÀ-ÝŐŰẞŒ]))(?=(?!.*[- '][- ']))[A-ZÀ-ÝŐŰẞŒß-ÿőűœa-z- ']{2,}([a-zß-ÿőűœ]|(, Jr.))$

function myFunction() {
    
  const pattern = "^(?=([A-ZÀ-ÝŐŰẞŒ]|([a-zß-ÿőűœ][ '])))(?=(?![a-zß-ÿőűœ]+[A-ZÀ-ÝŐŰẞŒ]))(?=(?!.*[A-ZÀ-ÝŐŰẞŒ][A-ZÀ-ÝŐŰẞŒ]))(?=(?!.*[- '][- ']))[A-ZÀ-ÝŐŰẞŒß-ÿőűœa-z- ']{2,}([a-zß-ÿőűœ]|(, Jr.))$";
    var regex = new RegExp(pattern, 'gm');
    var a = document.getElementById("myText");
  var b = a.value;
  var c = regex.test(b);
  var d = document.getElementById("result") ;
  d.innerHTML = "Result:";
  if(b != ""){
      if(c){
          d.innerHTML += " passed";
      }
      else{
        d.innerHTML += " failed";
        }
  }
  else{
    return
  }
}
input[type=text] {
  width: 99%;
  padding: 4px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
button {
  background-color: #04AA6D;
  color: white;
  padding: 4px;
  border: none;
  cursor: pointer;
  width: 25%;
}

button:hover {
  opacity: 0.8;
}
<h2>Name Validation Regex Pattern </h2>
<div class="container">
      <label for="name"><b>Name</b></label>
        <input type="text" id="myText"  placeholder="Enter Your Name" name="name" value="">
</div>
 <div class="container">

<button onclick="myFunction()">Try it</button>
<p id="result"> Result: </p>
</div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

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}$");

6 Comments

do you really need ^ and $ when using matches? and some explanation would be nice...
Thanks, I have a quick question. It seems kind of backwards when looking at it. Is there a reason you listed the negative look-ahead before the [a-z .,'-]?
@Carlos Heuberger This could have been written in different ways. I just modified the user's expression to satisfy some of the conditions it missed.
@oznomal Yes, because the look-ahead determines whether it's the last character that is to be matched and if that is, it's not one of those. It has to placed before matching the last character, because it is a "look ahead". If you put it afterwards, there's no character "ahead" of you to match. As Carlos Heuberger pointed out, you can also omit ^ and the last $ when using matches.
sure it can be written in different ways, but I would like to know why use ^ and $ - is it needed? and, by the way, this expression also returns true for names (much) longer than 25 characters... but seems like that is OK for @oznomal (should correct the question)
|
0

A regex for the same:

([a-zA-z]{1}[a-zA-z_'-,.]{0,23}[a-zA-Z]{0,1})

8 Comments

{1} really needed? I believe that [a-zA-Z] only matches one character by itself... the - inside of [] also has a special meaning, not sure if the author meant it... and this expression seams to match "a_"
This means the Name should end with a character.
but "a_"does not end with a character but your expression accept it! (or "test,")
([a-zA-z]{1}[a-zA-z_'-,.]{0,23}[a-zA-Z]{1}) this regex is correct or not.
what about one letter names?
|
0

Lets change the order of the requirements:

  1. ignore case: "(?i)"
  2. can only start with an a-z character: "(?i)[a-z]"
  3. can only end with an a-z: "(?i)[a-z](.*[a-z])?"
  4. is between 1 and 25 characters: "(?i)[a-z](.{0,23}[a-z])?"
  5. can contain a-z and [ '-,.]: "(?i)[a-z]([- ',.a-z]{0,23}[a-z])?"

the last one should do the job:

valid = name.matches("(?i)[a-z]([- ',.a-z]{0,23}[a-z])?")

Test on RegexPlanet (press java button).

Notes for above points

  1. could have used "[a-zA-Z]"' instead of"(?i)"'
  2. need ? since we want to allow one character names
  3. 23 is total length minus first and the last charracter (25-1-1)
  4. the - must come first (or last) inside [] else it is interpreted as range sepparator (assuming you didn't mean the characters between ' and ,)

Comments

0

Try this simplest version:

^[a-zA-Z][a-zA-Z][-',.][a-zA-Z]{1,25}$

Thanks for sharing.

Comments

0

A unicode compatible version of the answer of @ProPhoto:

^[^- '](?=(?!\p{Lu}?\p{Lu}))(?=(?!\p{Ll}+\p{Lu}))(?=(?!.*\p{Lu}\p{Lu}))(?=(?!.*[- '][- '.]))(?=(?!.*[.][-'.]))(\p{L}|[- '.]){2,}$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.