How to validate a letter and whitespace only input via JavaScript regular expression

You can use javascript test() method to validate name field. The test() method tests for a match in a string.

/^[A-Za-z\s]+$/.test(x) //returns true if matched, vaidates for a-z and A-Z and white space

or

/^[A-Za-z ]+$/.test(x)

If you are building something for modern browsers, there is something very pleasurable in HTML5:

<input id="username" name="name" type="text" pattern="[a-zA-Z]{5,}" title="Minimum 5 letters" required />

Reference: HTML5 forms input types

Update 2017/01/17:

Old browsers are quite weak on the market shares nowadays. This is a good practice to use HTML5 features instead of compatibility scripts.


check out regular expressions and patterns.

function f1() 
{  
   var x=document.f.name.value;  
   return /^[A-z ]+$/.test(x);
}