Reputation: 873
I have a form that accepts name, phone no. Currently, I have done validation for non empty fields. I want to add validation for name (alphabets) and phone no.(numbers).
My current code is given below. On submitting the form, I will be calling validateform()
function:
function validateform()
{
var str= true;
document.getElementById("name").innerHTML="";
if(document.frm.name.value=="")
{
document.getElementById("name").innerHTML="Please enter Name";
str=false;
}
return str;
}
The value entered for name should be only alphabets. If not, I want to show the message "enter only alphabets". How should I do it?
Upvotes: 2
Views: 15304
Reputation: 683
/*mobile number of 10 digits */
var digit=10;
var pattern=/[0-9]{digit}/;
if(!pattern.match ( phoneno ) )
alert("not a valid number");
Upvotes: 2
Reputation: 26
function alphanumeric(inputtxt)
{
var letters = /^[0-9a-zA-Z]+$/;
if(inputtxt.value.match(letters))
{
alert('Your registration number have accepted : you can try another');
document.form1.text1.focus();
return true;
}
else
{
alert('Please input alphanumeric characters only');
return false;
}
}
See more here.
Upvotes: 1
Reputation: 1598
var alphaExp = /^[a-zA-Z]+$/;
if(!document.frm.name.match(alphaExp))
{
document.getElementById("name").innerHTML="Please enter only alphabets";
str=false;
}
var numExp = /^[0-9]+$/;
if(!document.frm.phone.match(numExp))
{
document.getElementById("phone").innerHTML="Please enter only numbers";
str=false;
}
With this you don't need to check for empty input. If you want to handle empty input separately, replace +
with a *
in the regexes.
Upvotes: 1
Reputation: 151
You could use regex to achive what you're trying to do.
function validatePhonenumber(value) {
var regexp = /^[0-9]+?$/;
return regexp.test(value);
}
function validateAlphabet(value) {
var regexp = /^[a-zA-Z ]*$/;
return regexp.test(value);
}
Upvotes: 1
Reputation: 15148
As noted in the comments, you can try something like this:
var rule = /^[a-zA-Z]*$/;
if(rule.test(document.frm.name.value)) {
// this contains only letters !
}
Upvotes: 1