如何在我的jsp页面上设置手机号码验证



我正在使用这个脚本进行验证,有人能帮我找出错误的地方吗。我用这个来验证手机号码。当我用jquery运行这个代码时,它不起作用。

function mobilenumber() {
if(document.getElementById('mobnum').value != ""){
var y = document.getElementById('mobnum').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Invalid Mobile No.");
document.getElementById('mobnum').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Mobile No. should be 10 digit");
document.getElementById('mobnum').focus();
return false;
}
if (!(y.charAt(0)=="9" || y.charAt(0)=="8" || y.charAt(0)=="7"))
{
alert("Mobile No. should start with 9 ,8 or 7 ");
document.getElementById('mobnum').focus();
return false
}
}
}
<input type="submit" value="INSERT"class="btn"onclick="submitForm();">

jquery是

$(document).ready(function(){
function submitForm(){
if(mobilenumber()){
$('#form1').submit(function(){
});
}
else{
alert("Please Input Correct Mobile Numbers");
}
}
});   

使用HTML5模式

<input type="number" pattern=".{10}" title="Enter Valid Mob No" required>
var mobile = document.getElementById("mobnum").value;
var numericmob = isNumber(mobile );
if(!numericmob)
{
alert("Enter only positive numbers into the Contact Number field.");      
return false;
}
if(mobile.length!=10)
{
alert("Enter 10 digits Contact Number.");
return false;
}

//检查元素是否为数字的写入函数

function isNumber(elem)
{    
var re = /^[0-9]+$/; 
str = elem.toString();
if (!str.match(re)) 
{               
return false;
}
return true;
}

此功能的优点是您可以使用它来检查表单上的任何数字字段,如id、金额等。

在验证为真后,使用jQUery.submit()函数提交表单

<form id="myForm" action="abc.php" method="post">
<!-- Your Form -->
<button onclick="submitForm();">Submit</button>
</form>

现在在这里检查表单数据是否有效

function submitForm(){
if(mobilenumber()){
$('#myForm').submit();
}
else{
alert("Please Input Correct Mobile Numbers");
}
}

编辑:使用@Aniket的isNumber函数检查手机号码字段中的长度和数字。哪个更通用。

if(document.getElementById('mobile_number').value != ""){
var y = document.getElementById('mobile_number').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Invalid Mobile No.");
document.getElementById('mobile_number').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Mobile No. should be 10 digit");
document.getElementById('mobile_number').focus();
return false;
}
if (!(y.charAt(0)=="9" || y.charAt(0)=="8" || y.charAt(0)=="7"))
{
alert("Mobile No. should start with 9 ,8 or 7 ");
document.getElementById('mobile_number').focus();
return false
}

}

试试这个。。。这对你来说是必要的。。。如果你正在寻找ragex图案,那么就用这个。。。。

^([0|+[0-9]{1,5})?([7-9][0-9]{9})$

最新更新