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.
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>
please suggest for the regular expression for the capitalization of each word in the input tag
Thanks Uwe!
“^[a-zA-Z]+( [a-zA-Z]+)+$” works in Java as well for names with multiple words!
Another variation:
^[ a-zA-Z\-\’]+$
Will match:
O’Mally-Brient von M’ar III
The regular expression /^[a-zA-Z]+( [a-zA-Z]+)+$/ allows for names with more than 2 words, i.e. “Erwin van der Groot”.
like the code..it is worth for me