Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate a full name input in a form using javascript?

Tags:

javascript

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?

like image 952
Mirko Avatar asked Dec 06 '22 03:12

Mirko


2 Answers

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'- ]+$/ 
like image 113
Robusto Avatar answered Dec 09 '22 14:12

Robusto


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>
&nbsp;&nbsp;
<button type="reset">Reset</button>
</form>
like image 20
James Anderson Jr. Avatar answered Dec 09 '22 15:12

James Anderson Jr.