文本框验证接受 javascript 中的端口 [英] textbox validation accepting Ports in javascript
问题描述
问题是在朋友的帮助下接受一个或多个端口之间有一个空格,我用这个来回答我的问题,但例如,如果我输入 88888,它会提醒我这样的事情:88888NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN 不正确
the question was accepting one or many ports that has one space between them with help of friends, 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
我该如何纠正这个问题
<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!');
}
推荐答案
没有太多错误检查的粗略正则表达式是: exp =/\d{1,5}/g
然后调用 .match(exp)
在你的字符串上.但是,您需要使用 parseInt 将输出转换为数字,以便您可以根据约束检查它的值.
A crude regex without much error checking would be: exp = /\d{1,5}/g
and then call .match(exp)
on your string. However, you will need to use parseInt to convert the output to a number so that you can check it's value against your constraints.
我认为如果没有正则表达式,您可以更轻松地做到这一点.一些拆分和解析字符串的快速代码是:
I think you may be able to do this easier without Regex. Some quick code to split and parse a string is:
var s = "21 456 -32 70000";
var parts = s.split(' ');
var output;
for(i in parts)
{
p = parseInt(parts[i]);
if( (0 <= p) && (p <= 65535) && !isNaN(p) )
output += p+"<br />";
}
希望这在某种程度上有所帮助.
Hopefully this helps to some degree.
这篇关于文本框验证接受 javascript 中的端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!