Regular expression for first and last name

后端 未结 24 1914
温柔的废话
温柔的废话 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:26

    Try these solutions, for maximum compatibility, as I have already posted here:

    JavaScript:

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

    HTML5:

    <input type="text" name="full_name" id="full_name" pattern="^(?:((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$" required>

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

    First name would be

    "([a-zA-Z]{3,30}\s*)+"
    

    If you need the whole first name part to be shorter than 30 letters, you need to check that seperately, I think. The expression ".{3,30}" should do that.

    Your last name requirements would translate into

    "[a-zA-Z]{3,30}"
    

    but you should check these. There are plenty of last names containing spaces.

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

    A simple function using preg_match in php

    <?php
    function name_validation($name) {
        if (!preg_match("/^[a-zA-Z ]*$/", $name) === false) {
            echo "$name is a valid name";
        } else {
            echo "$name is not a valid name";
        }
    }
    
    //Test
    name_validation('89name');
    ?>
    
    0 讨论(0)
  • 2020-11-22 10:29

    This is what I use.

    This regex accepts only names with minimum characters, from A-Z a-z ,space and -.

    Names example:

    Ionut Ionete, Ionut-Ionete Cantemir, Ionete Ionut-Cantemirm Ionut-Cantemir Ionete-Second
    

    The limit of name's character is 3. If you want to change this, modify {3,} to {6,}

    ([a-zA-Z\-]+){3,}\s+([a-zA-Z\-]+){3,}
    
    0 讨论(0)
  • 2020-11-22 10:30

    This regex work for me (was using in Angular 8) :

    ([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){2,30}
    

    It will be invalid if there is:-

    1. Any whitespace start or end of the name
    2. Got symbols e.g. @
    3. Less than 2 or more than 30

    Example invalid First Name (whitespace)

    Example valid First Name :

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

    For simplicities sake, you can use:

    (.*)\s(.*)
    

    The thing I like about this is that the last name is always after the first name, so if you're going to enter this matched groups into a database, and the name is John M. Smith, the 1st group will be John M., and the 2nd group will be Smith.

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