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.
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.
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 .
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 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