How to Validate First and Last Name using Regular Expression in PHP

When you allow the user to submit data on the server, it’s a good idea to validate data before further processing. A name field is a common form filed for a web application. Here we will show how you can validate the name filed to check whether the user provides their first and last name.

The Regular Expression (REGEX) is the easiest way to validate full name format in PHP. You can easily validate first and last name using regular expression in PHP. Use PHP preg_match() function to perform a regular expression match.

The following example code uses preg_match() function and simple REGEX for name validation in PHP.

preg_match("/^([a-zA-Z' ]+)$/","Given_Name");

Usage:

<?php
if(preg_match("/^([a-zA-Z' ]+)$/",$givenName)){
    echo 
'Valid name given.';
}else{
    echo 
'Invalid name given.';
}

2 Comments

  1. Adam Jimenez Said...
  2. Andrés Said...

Leave a reply

keyboard_double_arrow_up