Regular expression for first and last name

后端 未结 24 1915
温柔的废话
温柔的废话 2020-11-22 10:03

For website validation purposes, I need first name and last name validation.

For the first name, it should only contain letters, can be several words with spaces, an

相关标签:
24条回答
  • 2020-11-22 10:18

    I have created a custom regex to deal with names:

    I have tried these types of names and found working perfect

    1. John Smith
    2. John D'Largy
    3. John Doe-Smith
    4. John Doe Smith
    5. Hector Sausage-Hausen
    6. Mathias d'Arras
    7. Martin Luther King
    8. Ai Wong
    9. Chao Chang
    10. Alzbeta Bara

    My RegEx looks like this:

    ^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)
    

    MVC4 Model:

    [RegularExpression("^([a-zA-Z]{2,}\\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)", ErrorMessage = "Valid Charactors include (A-Z) (a-z) (' space -)") ]
    

    Please note the double \\ for escape characters

    For those of you that are new to RegEx I thought I'd include a explanation.

    ^               // start of line
    [a-zA-Z]{2,}    // will except a name with at least two characters
    \s              // will look for white space between name and surname
    [a-zA-Z]{1,}    // needs at least 1 Character
    \'?-?           // possibility of **'** or **-** for double barreled and hyphenated surnames
    [a-zA-Z]{2,}    // will except a name with at least two characters
    \s?             // possibility of another whitespace
    ([a-zA-Z]{1,})? // possibility of a second surname
    
    0 讨论(0)
  • 2020-11-22 10:21

    I'm working on the app that validates International Passports (ICAO). We support only english characters. While most foreign national characters can be represented by a character in the Latin alphabet e.g. è by e, there are several national characters that require an extra letter to represent them such as the German umlaut which requires an ‘e’ to be added to the letter e.g. ä by ae.

    This is the JavaScript Regex for the first and last names we use:

    /^[a-zA-Z '.-]*$/
    

    The max number of characters on the international passport is up to 31. We use maxlength="31" to better word error messages instead of including it in the regex.

    Here is a snippet from our code in AngularJS 1.6 with form and error handling:

    class PassportController {
      constructor() {
        this.details = {};
        // English letters, spaces and the following symbols ' - . are allowed
        // Max length determined by ng-maxlength for better error messaging
        this.nameRegex = /^[a-zA-Z '.-]*$/;
      }
    }
    
    angular.module('akyc', ['ngMessages'])
      .controller('PassportController', PassportController);
     
    .has-error p[ng-message] {
      color: #bc111e;
    }
    
    .tip {
      color: #535f67;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
    <script src="https://code.angularjs.org/1.6.6/angular-messages.min.js"></script>
    
    <main ng-app="akyc" ng-controller="PassportController as $ctrl">
      <form name="$ctrl.form">
    
        <div name="lastName" ng-class="{ 'has-error': $ctrl.form.lastName.$invalid} ">
            <label for="pp-last-name">Surname</label>
            <div class="tip">Exactly as it appears on your passport</div>
            <div ng-messages="$ctrl.form.lastName.$error" ng-if="$ctrl.form.$submitted" id="last-name-error">
              <p ng-message="required">Please enter your last name</p>
              <p ng-message="maxlength">This field can be at most 31 characters long</p>
              <p ng-message="pattern">Only English letters, spaces and the following symbols ' - . are allowed</p>
            </div>
            
            <input type="text" id="pp-last-name" ng-model="$ctrl.details.lastName" name="lastName"
                   class="form-control" required ng-pattern="$ctrl.nameRegex" ng-maxlength="31" aria-describedby="last-name-error" />
          </div>
    
          <button type="submit" class="btn btn-primary">Test</button>
    
      </form>
    </main>

    0 讨论(0)
  • 2020-11-22 10:21

    For first and last names theres are really only 2 things you should be looking for:

    1. Length
    2. Content

    Here is my regular expression:

    var regex = /^[A-Za-z-,]{3,20}?=.*\d)/

    1. Length

    Here the {3,20} constrains the length of the string to be between 3 and 20 characters.

    2. Content

    The information between the square brackets [A-Za-z] allows uppercase and lowercase characters. All subsequent symbols (-,.) are also allowed.

    0 讨论(0)
  • 2020-11-22 10:21
    var name = document.getElementById('login_name').value; 
    if ( name.length < 4  && name.length > 30 )
    {
        alert ( 'Name length is mismatch ' ) ;
    } 
    
    
    var pattern = new RegExp("^[a-z\.0-9 ]+$");
    var return_value = var pattern.exec(name);
    if ( return_value == null )
    {
        alert ( "Please give valid Name");
        return false; 
    } 
    
    0 讨论(0)
  • 2020-11-22 10:23

    After going through all of these answers I found a way to build a tiny regex that supports most languages and only allows for word characters. It even supports some special characters like hyphens, spaces and apostrophes. I've tested in python and it supports the characters below:

    ^[\w'\-,.][^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]]{2,}$
    

    Characters supported:

    abcdefghijklmnopqrstwxyz
    ABCDEFGHIJKLMNOPQRSTUVWXYZ
    áéíóúäëïöüÄ'
    陳大文
    łŁőŐűŰZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųū
    ÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁ
    ŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ.-
    ñÑâê都道府県Федерации
    আবাসযোগ্য জমির걸쳐 있는
    
    0 讨论(0)
  • 2020-11-22 10:26

    You make false assumptions on the format of first and last name. It is probably better not to validate the name at all, apart from checking that it is empty.

    0 讨论(0)
提交回复
热议问题