textbox validation accepting Ports in javascript
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: 开发者_如何学C88888NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN 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))
{
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!');
}
Unfortunately, regular expressions can't handle 'ranges', so you can't do this exactly as you want with regexp (therorically you can, but the regex would be hiper,hiper long).
However, you could validate your space-separated numbers with this regexp:
/^\d{1,5}([ ]\d{1,5})*$/
This will do what you want, except validating the range you supplied. But it controls that numbers have between 1 and 5 digits, and the other things you asked.
Hope this helps. Cheers
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.
I think you would compromise your performance here if you want you are trying to validate a simple Integer value via RegEx.
IMO, try spiting the string with Space (' ')
and and convert each value to Integer and perform myInt < 65535
.
for( String str : portNumbers.split(' ') ){
try{
int i = Integer.parseInteger( str );
if( 0 > i && i > 65535 ){
errorMessage = str + " is out of range.";
}
}catch (NumberFormatException e) {
errorMessage = str + " is not a valid port.";
}
}
(6553[0-5]|655[0-2][0-9]|65[0-4][0-9][0-9]|6[0-4][0-9][0-9][0-9]|\d{2,4}|[1-9])
精彩评论