How to Validate First and Last Name with Regular Expression using JavaScript

Before submitting the user’s input to the server side, it’s always a good approach to validate it on the client-side script. The Name input is a commonly used field for the HTML form of the web application. When you want the full name input from the user, the input value must be checked whether the user provides a valid name (first name and last name). Using JavaScript, the full name validation can be easily implemented in the form to check whether the user provides their first name and last name properly.

The REGEX (Regular Expression) is the easiest way to validate the Full Name (first name + last name) format in JavaScript. In the following code snippet, we will show you how to validate the first and last name with Regular Expressions using JavaScript.

  • test() – This function is used to perform a regular expression match in JavaScript.
var regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var name = document.getElementById('nameInput').value;
if(!regName.test(name)){
    alert('Invalid name given.');
}else{
    alert('Valid name given.');
}

The following code snippet shows how you can validate the input field for the full name in HTML form using JavaScript.

<p>Full Name: <input id="name" value=""></p>
<input type="button" onclick="validate();" value="Validate Name">
<script>
function validate(){
    var regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
    var name = document.getElementById('name').value;
    if(!regName.test(name)){
        alert('Please enter your full name (first & last name).');
        document.getElementById('name').focus();
        return false;
    }else{
        alert('Valid name given.');
        return true;
    }
}
</script>

5 Comments

  1. Balouch Yousif Said...
  2. Meepa Said...
  3. Jason Said...
  4. Uwe Said...
  5. Kritika Sharma Said...

Leave a reply

keyboard_double_arrow_up