问题是接受一个或多个端口之间有一个空格
在朋友的帮助下 here,我用这个作为答案 但是,例如,如果我输入88888,它会提醒我这样的事情:
88888NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN is not correct
我该如何纠正这个
<script type="text/javascript">
function portvalidating(field)
{
var output='';
m=field.value;
if(/^\d{1,5}([ ]\d{1,5})*$/.test(m))
{
var parts = m.split(' ');
for(i in parts)
{
var p= parseInt(parts[i]);
if(!((0 <= p) && (p<= 65535) && !isNaN(p)))
{
output+=p;
}
}
if(output=='')
var dummy=1;
else alert(output+'is not correct');
}
else alert('please enter a valid port!');
}
答案 0 :(得分:1)
尝试将您对读/写的关注点与来自警报的输入验证中的表单数据分开。这是在[0..65535]中验证一串空格分隔整数的函数的提示:
var getPorts = function(str) {
var ns=(""+str).split(/\s+/), ports=[], n, i;
for (i=0; i<ns.length; i++) {
n = parseInt(ns[i], 10);
if (isFinite(n) && !isNaN(n)
&& (ns[i]==n) // Make sure the number is an integer.
&& (n >= 0) && (n <= 65535)) {
ports.push(n);
}
}
return ports;
};
getPorts('-1 0 NaN 123 foo 255 99999'); // => [0, 123, 255]
答案 1 :(得分:0)
对于它的价值,这里是我的“回答”。它与发布的代码非常接近,但如所指出的那样存在差异。完成jsfiddle帖子。
// Returns: {ports, invalid}
// where ports are valid ports and invalid are ... not valid items.
function getPorts (inp) {
var invalid = [];
var ports = [];
// The /\s+/ ensures that multiple whitespace is skipped.
var split = inp.split(/\s+/);
for (var i = 0; i < split.length; i++) {
var str = split[i];
// It is generally best to *always* specify a base.
// (Otherwise it might be treated as hex or octal, which may or
// may not be okay. Adjust as required.)
var val = parseInt(str, 10);
// Need to make sure we have all digits.
// This is because parseInt("1foo2", 10) evaluates to 1
// and parseInt("8888NaN") evaluates to 8888
if (!str.test(/^\d+$/) || !(val >= 0 && val <= 0xffff)) {
invalid.push(str);
} else {
ports.push(val);
}
}
return {ports: ports, invalid: invalid};
}
// if r.invalid.length > 0 then it contained some "invalid" items.
// it may also be "invalid" if r.ports.length == 0
var r = getPorts("88888NaNNaN");
alert("ports: " + r.ports);
alert("invalid: " + r.invalid);
var r = getPorts("123 12345 88888 NaN NaN 1d234");
alert("ports: " + r.ports);
alert("invalid: " + r.invalid);
快乐的编码。
请根据maerics的帖子将其放入一个函数中。