开发者

textbox validation accepting IPs in javascript

I want to have a validation function it must accept 3 typ开发者_运维问答es:

var
portvar
ipvar

one of my problems is in IPvar user input must be in this syntax as example:

[192.168.1.0/24,10.1.1.0/24]

how can I accept just such Ips from textboxes?


You could check it against a regular expression like this:

var textVal = ...;
if ((/^\[(?!,)(,?(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\/[1-9]\d*)+\]$/).test(textVal)) {
  alert('Valid!');
}
else {
  alert('Invalid!');
}

The regular expression identifies valid IP's with each part of the IP being a number between 0 and 255. Additionally, as your example shows, each IP must be followed by a single / and then a number representing the subnet mask. Lastly, multiple IPs are separated by commas (however the regular expression does not allow a comma at the very beginning or the very end).

(By the way, the second IP address in your example isn't valid).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜