Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an input type="text" for names in my HTML code. I need to make sure that it is a string with letters from 'a' to 'z' and 'A' to 'Z' only, along with space(s).

This is my HTML code:

<form action="" name="f" onsubmit="return f1()">
                Name : <input type="text" name="name">

I'm expecting my JavaScript to be something like this:

function f1() 
{  
   var x=document.f.name.value;  
   ..... 
   ..... 
   return false;
}

PS: I'm not really familiar with Regular Expressions, so please do put up an explanation with the code.

like image 371
Zoran777 Avatar asked Jul 27 '13 14:07

Zoran777


People also ask

How do I make an input field accept only letters in JavaScript?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

How do you check if a string contains only alphabets and numbers in JavaScript?

The RegExp test() Method To check if a string contains only letters and numbers in JavaScript, call the test() method on this regex: /^[A-Za-z0-9]*$/ . If the string contains only letters and numbers, this method returns true . Otherwise, it returns false .


1 Answers

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)
like image 80
Konsole Avatar answered Oct 04 '22 14:10

Konsole