javascript IP 地址验证,中间有适当的点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17987015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IP address validation with proper dots in between
提问by RONE
I wanted to validate only for IP address accepting only 3 three dots after some numbers
我只想验证 IP 地址只接受一些数字后的 3 个三个点
ex: Valid: 191.123.121.202 is valid which has 3 dots after some decimal. Invalid : 191..123.121.202 is invalid where 2 dots are in sequence
例如:有效:191.123.121.202 是有效的,在小数点后有 3 个点。无效:191..123.121.202 无效,其中 2 个点按顺序排列
Whole Point: wanted a robust IP validator
重点:想要一个强大的 IP 验证器
$("input.onlynumberdecimal").keydown(function (event) {
console.log(event.keyCode);
if (event.shiftKey == true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {
} else {
event.preventDefault();
}
if($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
event.preventDefault();
//if a decimal has been added, disable the "."-button
});
TO some extent i have got with the help of some other site. And also wanted if the user copy and paste the correct IP, then it should accept, else it should not allow him to paste.
在某种程度上,我得到了其他网站的帮助。并且还想如果用户复制并粘贴正确的IP,那么它应该接受,否则它不应该允许他粘贴。
回答by Tushar Gupta - curioustushar
try this
试试这个
var pattern = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
x = 46;
$('input[type="text"]').keypress(function (e) {
if (e.which != 8 && e.which != 0 && e.which != x && (e.which < 48 || e.which > 57)) {
console.log(e.which);
return false;
}
}).keyup(function () {
var this1 = $(this);
if (!pattern.test(this1.val())) {
$('#validate_ip').text('Not Valid IP');
while (this1.val().indexOf("..") !== -1) {
this1.val(this1.val().replace('..', '.'));
}
x = 46;
} else {
x = 0;
var lastChar = this1.val().substr(this1.val().length - 1);
if (lastChar == '.') {
this1.val(this1.val().slice(0, -1));
}
var ip = this1.val().split('.');
if (ip.length == 4) {
$('#validate_ip').text('Valid IP');
}
}
});
Update for validating IP address with port numbers.
使用端口号验证 IP 地址的更新。
Ex. 192.168.2.100:27896
前任。192.168.2.100:27896
var pattern = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\:([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\b/;
x = 46;
$('input[type="text"]').keypress(function (e) {
console.log(e.which);
if (e.which != 8 && e.which != 0 && e.which != x && e.which !=58 && (e.which < 48 || e.which > 57)) {
console.log(e.which);
return false;
}
}).keyup(function () {
var this1 = $(this);
if (!pattern.test(this1.val())) {
$('#validate_ip').text('Not Valid IP');
while (this1.val().indexOf("..") !== -1) {
this1.val(this1.val().replace('..', '.'));
}
x = 46;
} else {
x = 0;
var lastChar = this1.val().substr(this1.val().length - 1);
if (lastChar == '.') {
this1.val(this1.val().slice(0, -1));
}
var ip = this1.val().split('.');
if (ip.length == 4) {
$('#validate_ip').text('Valid IP');
}
}
});
回答by Rajniprabha
use regex for this and regex for ipv4 address is
为此使用正则表达式,对 ipv4 地址使用正则表达式是
/((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.|$)){4}/
/((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.|$)){4}/
function validateIP(ipAddress){ ipv4Re = new RegExp('^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}', 'i'); if(ipv4Re.test(ipAddress)){ return "its a vaild address"} else return "its an invalid address"}
it will validate :
它将验证:
- 0.0.0.0
- 255.255.255.255
- 191.123.121.202
- 0.0.0.0
- 255.255.255.255
- 191.123.121.202
and invalidate: - 191..123.121.202
并无效: - 191..123.121.202
回答by Mike Samuel
function isIpAddress(s) {
if (typeof s !== 'string') { return false; }
// There must be 4 parts separated by dots.
var parts = s.split('.');
if (parts.length !== 4) { return false; }
// Each of the four parts must be an integer in the range 0 to 255.
for (var i = 0; i < 4; ++i) {
var part = parts[i];
// Each part must consist of 1 to 3 decimal digits.
if (!/^\d{1,3}$/.test(part)) { return false; }
var n = +part;
if (0 > n || n > 0xff) { return false; }
}
return true;
}
回答by HymanSparrow
Try this.
试试这个。
<SCRIPT language="JavaScript">
function verifydata( incoming )
{
errorlog = ""
// CHECK ALL THE FIELDS TO VERIFY THEIR EXISTENCE
if ( incoming.ipstart.value == "" )
errorlog += "Starting IP Address is blank.\n"
if ( incoming.ipend.value == "" )
errorlog += "Ending IP Address is blank.\n"
if ( !(/^(?:(?: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]?)$/.test(incoming.ipstart.value) ) )
errorlog += "Incorrect Starting IP Address Format.\n"
if ( !(/^(?:(?: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]?)$/.test(incoming.ipend.value) ) )
errorlog += "Incorrect Ending IP Address Format.\n"
}
</SCRIPT>
回答by fahadash
OR You can use the jQuery Mask Plugin. So simple to use and it will add the . (dots) and placeholders for numbers would be marked.
或者您可以使用jQuery Mask Plugin。使用起来如此简单,它会添加 . (点)和数字占位符将被标记。
回答by rvishal
Following solution will validate the entered IP address value including format & it's value also. It will accept min 0.0.0.0 and max 255.255.255.255. If invalid IP address entered then code will highlight the input control in pink color & clear the text otherwise will keep valid value as entered.
以下解决方案将验证输入的 IP 地址值,包括格式及其值。它将接受最小 0.0.0.0 和最大 255.255.255.255。如果输入的 IP 地址无效,则代码将以粉红色突出显示输入控件并清除文本,否则将保持输入的有效值。
Put the input tag on page:
将输入标签放在页面上:
<input type="text" name="IpAddress" id="IpAddress" class="input-medium" onkeypress="return IPAddressKeyOnly(event)" onblur="confirmIPAddress();"/>
Add following methods in appropriate java script file or include on the page it self.
在适当的 java 脚本文件中添加以下方法或将其包含在页面上。
1) To handle the key press event:
1) 处理按键事件:
function IPAddressKeyOnly(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
if (keyCode != 46 && keyCode > 31 && (keyCode < 48 || keyCode > 57))
return false;
return true;
}
2) To handle the correct IP address value validation:
2) 处理正确的 IP 地址值验证:
function confirmIPAddress() {
var ip = document.getElementById("IpAddress");
if (ip.value.length >0 && ip.value.length<=15 ) {
ip.style.background = "white";
var ipSlot=ip.value.split(".");
if(ipSlot.length==4){
for (var i=0;i<ipSlot.length;i++){
var l=ipSlot[i].length;
if (l >0 && l<=3){
if(ipSlot[i]>=0 && ipSlot[i]<256){}
else{ip.value = "";ip.style.background = "pink";break ;return false;}
}else{
ip.value = "";ip.style.background = "pink";break ;return false;
}
}
}else{ip.value = "";ip.style.background = "pink";return false; }
}
else{ip.value = "";ip.style.background = "pink";}
}
}
回答by Javeed
try it once .
尝试一次。
//Check Format
var ip = ip.split(".");
if (ip.length != 4) {
return false;
}
//Check Numbers
for (var c = 0; c < 4; c++) {
//Perform Test
if(isNaN(parseFloat(ip[c])) || !isFinite(ip[c]) || ip[c] < 0 || ip[c] > 255 || ip[c].indexOf(" ") !== -1 || ip[c].match(/^-\d+$/)){
return false;
}
}
return true;
回答by Mr.Jhon
//invalid ip send
ipvalidation('256.0.0.0');
//ip validation function
function ipvalidation(x){
limit = 255;
[ii, xx, yy, cc] = x.split('.');
if(ii <= limit && xx <= limit && yy <= limit && cc <= limit){
alert('valid ip');
} else {
alert('invalid ip');
}
}
回答by hitautodestruct
Not using regex
不使用正则表达式
Just putting another one in here that is slightly more verbose but still a small implementation:
只是在这里放另一个稍微冗长但仍然是一个小实现:
let isIpv4 = ip => {
// Test length to see that we have a valid ipv4 address
// Must consist of 4 values seperated by .
// Each char must be a number between 0 and 255 and not empty
return ip !== '' && ip.split('.').filter( n => ( n !== '' && n >= 0 && n <= 255 ) ).length === 4
}
console.log(isIpv4('192.168.2.1')) // True
console.log(isIpv4('255.255.255')) // False
console.log(isIpv4('255.ab.255.255')) // False