How to allow only one space in full name field using JavaScript

Some times we need to force customer to enter the details as required by our system. We can validate the input using regular expression in JavaScript and alert the visitor of the problem. Use the following JavaScript function to check for valid full name which has only one space in between. The same function can also be used to disallow space at the start of the full name.

function validateName(val) {
	if(val.match(/^[a-zA-Z]+[\s]([a-zA-Z]+)$/)) {
		return "Correct";
	} else {
		return "Incorrect";
	}
}

// Function will return Incorrect for the following name
alert(validateName("Adam"));

// Function will return Incorrect for the following name
alert(validateName("Adam Sandler Thomas"));

// Function will return Incorrect for the following name
alert(validateName(" Adam Sandler "));

// Function will return Correct for the following name
alert(validateName("Adam Sandler"));
Please follow and like us:

Be the first to comment

Leave a Reply

Your email address will not be published.


*