the question was accepting one or many ports that has one space between them
with help of friends here, I used this one for my answer but for example if I enter 88888 it will alert me such this thing:
88888NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN is not correct
how can I correct this
<script type="text/javascript">
function portvalidating(field)
{
var output='';
m=field.value;
if(/^\d{1,5}([ ]\d{1,5})*$/.test(m))
开发者_StackOverflow中文版 {
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!');
}
Try separating your concerns of reading/writing to form data from input validation from alerting. Here is a hint on the function to validate a string of space separated integers in [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]
For what it's worth, here my "answer". It is very close to the code posted, but there are differences as noted. Complete with a jsfiddle post.
// 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);
Happy coding.
Please put this in a function, as per maerics's post.
精彩评论