phpregexvalidationtitle-case

Validate that form field input is Title Case formatted


I am trying to make an input with regex for the following pattern:

<input type="text" name="display_name" placeholder="Display Name" id="display_name" required minlength="1" maxlength="32" 
pattern="[A-Z].{1,1}[a-z1-9\W_]).{,}[ ]{,}[A-Z].{1,1}[a-z1-9\W_]).{,}[ ]{,}[A-Z].{1,1}[a-z1-9\W_]).{,}[ ]{,}">

Also, if you can do this pattern, can I also get the same pattern to use for php pregreplace.


Solution

  • As pointed out in the comments, the older regex has some problems. So, you can try this new regex.

    /^[A-Z](?:[a-z0-9\W_]+)(?:\s+[A-Z](?:[a-z0-9\W_]+(?=[A-Z]|\s|$))*)$/
    

    This is a fiddle showing some test cases.

    And here is the PHP in which this regex can be used.

    $input = "YourInputStringHere";
    
    $pattern = '/^[A-Z](?:[a-z0-9\W_]+)(?:\s+[A-Z](?:[a-z0-9\W_]+(?=[A-Z]|\s|$))*)$/';
    
    if (preg_match($pattern, $input)) {
        echo "Valid input!";
    } else {
        echo "Invalid input!";
    }
    

    And if you want to convert this into function, then try following:

    function isValidName($name) {
        if ($name !== null && $name !== '') {
            $pattern = '/^[A-Z](?:[a-z0-9\W_]+)(?:\s+[A-Z](?:[a-z0-9\W_]+(?=[A-Z]|\s|$))*)$/';
            return preg_match($pattern, $name);
        }
        return false;
    }
    

    And, if you want to use Javascript to force the input to follow the regex, you can try the following:

    document.getElementById('display_name').addEventListener('input', function() {
        // This will convert all letters to lowercase except the first letter of word.
        this.value = this.value.toLowerCase().replace(/\b\w/g, function (char) {
            return char.toUpperCase();
        });
    });
    

    And the error_message is just a span. Also, after this Javascript, I don't think you would need the pattern thing in your input. So, if you are using this Javascript, you can remove the pattern from your input.

    Hope this helps.