我想验证电话号码的文本框。 它应该接受所有国家的电话号码。
这是我的代码:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script>
$.validator.addMethod("regx", function(value, element, regexpr) {
return regexpr.test(value);
}, "Letters only");
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#register-form").validate({
rules: {
phoneno:{
required:true,
regx:/^(?![8]{10}|[9]{10})[7-9]{1}[0-9]{9}$/,
minlength:10,
maxlength:14,
}
},
messages: {
{
required:"<font color='red'>Phone number is Required</font>",
regx:"<font color='red'>Enter only Numbers</font>",
minlength:"<font color='red'>Minimum length is 10 </font>",
maxlength:"<font color='red'>Maximum length is 14 </font>",
}
},
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
<input id="phoneno" type="text" placeholder="phone no..." class="form-control input-small" value="" name="phoneno">
答案 0 :(得分:2)
试试这个......
<form id="myform">
<input type="text" name="field1" id="field1" class="required" />
<input type="submit" />
</form>
$.validator.addMethod('customphone', function (value, element) {
return this.optional(element) || /^(\+91-|\+91|0)?\d{10}$/.test(value);
}, "Please enter a valid phone number");
$(document).ready(function () {
$("#myform").validate({
rules: {
field1: 'customphone'
}
});
});
http://jsfiddle.net/s82em3wx/1/
接受
+ 91xxxxxxxxxx
+ 91-XXXXXXXXXX
0xxxxxxxxxx
XXXXXXXXXX
答案 1 :(得分:1)
你可以看到这个演示
function validatePhone(txtPhone) {
var a = document.getElementById(txtPhone).value;
var filter = /^[0-9-+]+$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
}
$('#txtPhone').blur(function(e) {
if (validatePhone('txtPhone')) {
$('#spnPhoneStatus').html('Valid');
$('#spnPhoneStatus').css('color', 'green');
}
else {
$('#spnPhoneStatus').html('Invalid');
$('#spnPhoneStatus').css('color', 'red');
}
});