Reputation: 609
Here is a validation code that I use to validate mobile number. If I enter a mobile number with alphabets or any invalid number, it accepts that too. Can someone suggest what is wrong in this?
Thanks
var g=document.getElementById('mobile').value;
if (g.length == 0 )
{
alert( "Please Enter Mobile Number." );
formn.mobile.focus();
return false;
}
if(g.length>0)
{
if((g.length<10)||(g.length>10))
{
alert( "Mobile number should be 10 digits");
document.getElementById('mobile').focus();
return false;
}
else
{
var h3=/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/;
if(g.match(h3)!=null)
{
alert( "Please Enter Valid Mobile Number");
document.getElementById('mobile').focus();
return false;
}
}
}
EDIT : I was thinking of removing the condition of 10 digits and allow user to input the mobile numbers as per their choice and their own way and then replace/reformat using a regex so that only 10 digits mobile number goes into the database. During google search I found somewhere on stackoverflow that ^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$
works well for reformating in following scenarios. Appreciate if someone can help me reformat it and show the reformatted digits when the user goes into the next textbox (losing focus)
9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344
Upvotes: 2
Views: 717
Reputation: 11
This regular expression fits for all use-cases you mentioned and strictly rejects other patterns.
((00)|\+|0)?((91)|0)?\s{0,2}-?\s{0,2}(\d{10})
Upvotes: 1
Reputation: 13000
why not just use [0-9] as a regex, basicly if it is not in 0-9 it is invalid, maybe you want + for international calls that is 00 infront of phone number..
Please check out these testers also if you have not already:
var re = /[0-9+]/g;
var str = '0700';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
If it is not in found with /[0-9+]/g
it is not legal
Upvotes: 2
Reputation: 2121
Use Below code :-
var g=document.getElementById('mobile').value;
if (g.length == 0 )
{
alert( "Please Enter Mobile Number." );
formn.mobile.focus();
return false;
}
if(g.length>0)
{
if((g.length<10)||(g.length>10))
{
alert( "Mobile number should be 10 digits");
document.getElementById('mobile').focus();
return false;
}
else
{
var h3=/^[1-9]{1}[0-9]{9}$/;
if(h3.test(document.getElementById('mobile').value) == false)
{
alert( "Please Enter Valid Mobile Number");
document.getElementById('mobile').focus();
return false;
}
}
}
Updated your regex code.
Upvotes: 2