I would like to write a function to validate a full name input in a form with Javascript:
a single word will be ok, a string with some blank character among name surname, middle name too, but I do not want any digit.
Any suggestion?
There are several ways to write this, but, simply, the regular expression
/^[a-zA-Z ]+$/
should work for you. It will find any combination of alpha characters and spaces but no digits.
Edit to add the information from my comment, which I feel is important:
You may also wish to add the apostrophe and hyphen between the brackets, since Irish and Italian names include the former (O'Donnell, D'Ambrosio) and some folks have hyphenated last names (Claude Levi-Strauss, Ima Page-Turner, etc.).
This would result in the following expression:
/^[a-zA-Z'- ]+$/
Try this RegEx for maximum compatibility:
Don't forget to escape the single quote-marks (') if you put this in a JavaScript string enclosed with single quotes.
^(?:((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$
Example:
function checkName(eid){ alert(/^(?:((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$/.test(document.getElementById(eid).value)? 'Congratulations! You entered a valid name.' : 'Sorry, You entered an invalid name. Please try again.');};
*
{
color:#535353;
font-family:Arial, Helvetica, Sans-Serif;
}
input:valid
{
background-color: #DEFFDF;
}
input:invalid
{
background-color: #C7D7ED;
}
<form action="#" method="post" onsubmit="checkName('full_name');return false;">
<label for ="full_name">Your Name: </label>
<input type="text" name="full_name" id="full_name" maxlength="85" pattern="^(?:((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$" title="Please enter your FULL name." style='width:200px;height:auto;' required>
<br><br>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With