这是一篇较旧的帖子,但是对于想要一种简单的方法来操作多个输入的人,而不使用膨胀插件,或者不必担心文档或方法,这里有一个简单的类选择器方法,可以为您完成这一切。它只支持 IPv4,但听起来您的需求很简单。
//jQuery 1.9+ selector pattern,
//To get working with an older version
//Swap first line to $(".ip").bind('keydown',function(e){
//To get working with jQuery versions support .live
//$(".ip").live('keydown',function(e){
$(document).on('keydown',".ip",function(e){
var code = e.keyCode || e.which;
var sections = $(this).val().split('.');
//Only check last section!
var isInt = ((code >= 48 && code <= 57) || (code >= 96 && code <= 105));
var hasSlash = $(this).val().indexOf("/") == -1;
if(isInt){
if(hasSlash){
if(sections.length < 4){
//We can add another octet
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
$(this).val($(this).val()+"."+String.fromCharCode(code));
return false;
}
return true;
} else {
//Lets prevent string manipulations, our string is long enough
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
return false;
}
return true;
}
} else {
var cidr_split = $(this).val().split('/');
var target_val = parseInt(cidr_split[1]+String.fromCharCode(code));
return (target_val < 33 && target_val.toString().length < 3 && parseInt(cidr_split[1]) != 0);
}
} else if(code == 191){
//CIDR Slash
return ($(this).val().indexOf("/") == -1);
} else if(code == 8 || code == 46 || code == 9 || code == 13){
return true;
}
return false
});
为了理解这一点,您在输入中绑定类“ip”,它将自动处理其余部分:D 此版本支持 CIDR 表示法(例如:192.168.1.1/16)它只允许有效地址输入,要删除 CIDR 功能,您可以使用以下 sn -p(未测试)
//jQuery 1.9+ selector pattern,
//To get working with an older version
//Swap first line to $(".ip").bind('keydown',function(e){
//To get working with jQuery versions support .live
//$(".ip").live('keydown',function(e){
$(document).on('keydown',".ip",function(e){
var code = e.keyCode || e.which;
var sections = $(this).val().split('.');
//Only check last section!
var isInt = ((code >= 48 && code <= 57) || (code >= 96 && code <= 105));
if(isInt){
if(sections.length < 4){
//We can add another octet
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
$(this).val($(this).val()+"."+String.fromCharCode(code));
return false;
}
return true;
} else {
//Lets prevent string manipulations, our string is long enough
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
return false;
}
return true;
}
} else if(code == 8 || code == 46 || code == 9 || code == 13){
return true;
}
return false
});
我在这里提供代码有两个目的 1)这是我认为需要解决的问题,2)我希望为世界做出贡献
sn-p 不是设计用来拆开的,也不支持 IPv6,如果需要 IPv6 支持请看https://code.google.com/p/jquery-input-ip-address-control/anyulled 的建议。
但除了复杂的语法之外,它将八位字节分开,并且只检查“活动”八位字节,它支持任何有效地址(0.0.0.0、0.0.0.0/0 等),所以明智地使用它不会除了防止无效输入之外的任何花哨的检查。如果您正在寻找检查器,请参阅 Santiago Elvira Ramirez 关于 IP 地址验证器的帖子。