chevron_left
399 points
8 4 3

Name validation in javascript using regular expression

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 Expression 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.');
}
<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>

 

1 Comment

I&rsquo;m glad you covered the use of Regex in javascript. It is useful to know , not a lot of people understand it. I hope to see more post on Regex from you.

cheers

More Posts

Email id validation in javascript without regular expression. sanchi - May 8
Mobile number validation in javascript Sanjana Sagar - May 19
Regular expression for date format mm/dd/yyyy in Javascript DivyaN - Aug 15
Email id validation in JavaScript without regular expression sakshi - May 21
the name of the structure is referred to as its: C++ Lalit Kumar - Sep 9, 2020
modify the function to return true if the given number is an integer, and false otherwise. DivyaN - Aug 30
Login form in PHP and MySQL with Validation sakshi - Jul 2
How to find length of string in c++ using strlen Sanjana Sagar - May 22
Client side validation vs server side validation Hafsa_Rao - Aug 19
Client side validation and server side validation Saravana - May 19