我需要在我的项目中添加 IP 验证。jquery 或 jquery mobile 中是否有任何功能。这样它将验证输入字段?
谢谢
参考本文档 IP 验证
在这里,他使用了 jqueryvalidator.js 并举例说明。
$.validator.addMethod('IP4Checker', function(value) {
return value.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/);
}, 'Invalid IP address');
$('#form1').validate({
rules: {
ip: {
required: true,
IP4Checker: true
}
}
});
简短版本:
^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$
您可以使用正则表达式来测试 IP 是否有效:
"127.0.0.1".match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/);
这应该适用于IP地址
$.validator.addMethod('IP4Checker', function(value) {
var ip="^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
return value.match(ip);
}, 'Invalid IP address');
$('#remoteForm').validate({
rules: {
ipAddr: {
required: true,
IP4Checker: true
}
}
});
嗨,这是 IP 地址的最佳解决方案和掩码
$.validator.addMethod('IP4Checker', function(value) {
var ip = /^(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$/;
return value.match(ip);
}, 'Invalid IP address');
var $validator = $("#addCardForm").validate({
rules: {
txtIP: {
required: true,
IP4Checker: true
}
}
});
我通过以下方式使用 jQuery 验证插件:
$.validator.addMethod('IP4Checker', function(value) {
var ip = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
return value.match(ip);
}, 'Invalid IP address');
$('#form').validate({
rules:{
ip:{
required: true,
IP4Checker: true
}
}
});
希望有帮助。
/*
validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
validHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
*/
$.validator.addMethod('ipChecking', function(value) {
//var ip = "^(?:(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)\.){3}" +"(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)$";
validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
ipCheckFlag = true;
ipLists = value.split(',');
for(ip=0; ip<ipLists.length; ip++){
if(!ipLists[ip].trim().match(validIpAddressRegex)){
ipCheckFlag = false;
}
}
return ipCheckFlag;
});
除了@RAVI MONE 对带有子网掩码的 IP 地址的回答:
$.validator.addMethod('IP4Checker', function(value) {
var ip="^$|([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])((/([01]?\\d\\d?|2[0-4]\\d|25[0-5]))?)$";
return value.match(ip);
}, 'Invalid IP address.');
如果 IP 地址格式正确,则此函数返回true
,否则返回false
:
function isIpAddressValid(ipAddress) {
if (ipAddress == null || ipAddress == "")
return false;
var ip = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}' +
'(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$';
if (ipAddress.match(ip) != null)
return true;
}