JavaScript 只接受 0 到 255 之间的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13413320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript to accept only numbers between 0 to 255 range
提问by Sudhir
My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is entered beyond that it must alert a message.
我的要求是验证 ip 范围,我需要创建一个 JavaScript 函数来只接受数字,并且它必须只允许在 0 到 255 之间的范围内。如果输入任何超出该范围的内容,它必须发出一条消息。
I am currently using this below function
我目前正在使用以下功能
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
我是 JavaScript 新手,需要一些专家建议来解决我的需求。请给我建议
Thanks Sudhir
谢谢苏迪尔
采纳答案by Phil H
Currently you have the test
目前你有测试
(a < 48) || (a > 57)
for invalid values. So I would change those:
对于无效值。所以我会改变那些:
(a < 0 ) || (a > 255)
You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.
您可能还需要考虑如何处理 2.3 等非整数输入 - 要么舍入,要么将其视为无效。
At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value)
.
目前,正如 Kelvin Mackay 所指出的,您正在对 keypress 事件而不是输入值执行验证,因此将 onkeypress 更改为allownums(this.value)
.
I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.
我建议将警报更改为 div 中的警告,并使用验证来启用/禁用提交按钮,因为弹出窗口在几乎所有情况下都很烦人。
To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:
在输入无效条目时清除输入(如评论中所要求的)会使用户感到相当烦人;只要按下一个键来添加一个数字并使输入无效,整个输入就会被清除。但是,代码将是:
if(!validnum(this.value))
this.value="";
in the input tag, thus:
在输入标签中,因此:
<input type='text' id='numonly'
onkeyup='if(!validnum(this.value)) this.value="";'>
with the function changed to:
功能更改为:
function validnum(a) {
if(a < 0 || a > 255)
return false;
else
return true;
}
or more succinctly:
或更简洁地说:
function validnum(a) {
return ((a >= 0) && (a <= 255));
}
Edit: To alert and clear the box, if you must:
编辑:提醒并清除该框,如果您必须:
function validOrPunchTheUser(inputElement) {
if(!validnum(inputElement.value)) {
window.alert('badness'); // punch the user
inputElement.value = ""; // take away their things
}
}
<input type='text' id='numonly'
onkeyup='validOrPunchTheUser(this)'>
However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:
但是,阅读其他答案,显然您正在寻找验证八位字节(例如在 IP 地址中)。如果是这样,请在问题中说明这一点,因为它今天通过了我。对于八位字节:
function validateIPKeyPress(event) {
var key = event.keyCode;
var currentvalue = event.target.value;
if(key < 96 || key > 105)
{
event.preventDefault();
window.alert('pain');
return false;
}
else if(currentvalue.length > 2 ||
(currentvalue.length == 2 &&
key > 101)) {
window.alert('of death');
event.preventDefault();
event.target.value = event.target.value.substring(0,2);
}
else
return true;
}
With the input tag:
使用输入标签:
<input type='text' id='octet'
onkeydown='validateIPKeyPress(event)'>
Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";
.
除了请不要使用警报。如果你去掉警告线,它会默默地防止无效输入。请注意现在使用 onkeydown 的更改,以便我们可以捕获无效的按键操作并完全防止值更改。如果您必须清除输入,请执行if(!validateIPKeyPress(event)) this.value = "";
。
回答by Miroslav Holinka
I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.
我宁愿立即去验证整个 IP 地址。允许输入数字和点,通过 REGEX 模式解析它们。
Pattern usage example you could fetch here: http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
您可以在此处获取模式使用示例:http: //www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
The code itself would look something like:
代码本身看起来像:
<input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
function allowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46) // both nubmer range and period allowed, otherwise prevent.
{
e.preventDefault();
}
}
function checkIp()
{
var ip = $("#numonly").val();
/* The regular expression pattern */
var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
/* use javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(ip);
if(bValidIP){
// IP has ok pattern
$("#numonly").css("background", "green");
}
else {
$("#numonly").css("background", "red");
}
}
You could check it here on fiddle http://jsfiddle.net/Indias/P3Uwg/
你可以在这里查看小提琴 http://jsfiddle.net/Indias/P3Uwg/
回答by sandeep tiwari
function fun_key()
{
var key=event.keyCode;
if(key>=48 && key<=57)
{
return true;
}
else
{
return false;
alert("please enter only number");
}
}
and you can call this function on keypress event like:
<asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()"> </asp"textbox>
回答by Grant Miller
Single Integer
单整数
You can use the following solution to check if the user input for a single integeris between 0 - 255:
您可以使用以下解决方案来检查用户输入的单个整数是否介于 0 - 255 之间:
document.getElementById( 'example' ).addEventListener( 'input', event =>
{
const input = event.target.value;
console.log( /^\d+$/.test( input ) && input > -1 && input < 256 );
});
<input id="example" type="text" placeholder="Enter single integer" />
IP Address
IP地址
Alternatively, you can use the code below to verify that each section of an IP addressis between 0 - 255:
或者,您可以使用下面的代码来验证IP 地址的每个部分是否介于 0 - 255 之间:
document.getElementById( 'example' ).addEventListener( 'input', event =>
{
const input = event.target.value;
console.log( input === new Uint8ClampedArray( input.split( '.' ) ).join( '.' ) );
});
<input id="example" type="text" placeholder="Enter IP address" />
回答by Kelvin
You need to validate the current value of the input, rather than the last key that was pressed:
您需要验证输入的当前值,而不是最后按下的键:
<input type='text' id='numonly' onkeypress='allownums(this.value)'>
Your function then just needs to be modified to: if(a < 0 || a > 255)
您的函数只需要修改为: if(a < 0 || a > 255)
回答by Jamiec
A function like this should do it:
像这样的函数应该这样做:
function allownums(value){
var num = parseInt(value,10);
if(num <0 || num>255)
alert('invalid')
}
Then have your html look like:
然后让你的 html 看起来像:
<input type='text' id='numonly' onblur='allownums(this.value)'>
Live example: http://jsfiddle.net/USL3E/
现场示例:http: //jsfiddle.net/USL3E/
回答by Elias Van Ootegem
Update
I've set up a fiddlethat does some basic IP-formatting and checks weather or not all input is in range (0 - 255) etc... feel free to use it, improve it, study it... I've also updated the code snippet here to match the fiddle
更新
我已经设置了一个小提琴,它可以进行一些基本的 IP 格式化并检查天气或所有输入是否都在范围内(0 - 255)等......随意使用它,改进它,研究它......我'我还更新了此处的代码片段以匹配小提琴
There are several things you're not taking into account. First and foremost is that not all browsers have a keycode
property set on the event objects. You're better off passing the entire event object to the function, and deal with X-browser issues there.
Secondly, you're checking key after key, but at no point are you checking the actualvalue that your input field is getting. There are a few more things, like the use of the onkeypress
html attribute (which I don't really like to see used), and the undefined return value, but that would take us a little too far... here's what I suggest - HTML:
有几件事你没有考虑到。首先也是最重要的一点是,并非所有浏览器都keycode
在事件对象上设置了属性。您最好将整个事件对象传递给函数,并在那里处理 X 浏览器问题。
其次,您要检查一个又一个的键,但绝不会检查输入字段获得的实际值。还有一些其他的东西,比如使用onkeypress
html 属性(我真的不喜欢看到它被使用)和未定义的返回值,但这会让我们走得太远......这是我的建议 - HTML:
<input type='text' id='numonly' onkeypress='allowNums(event)'>
JS:
JS:
function allowNums(e)
{
var key = e.keycode || e.which;//X-browser
var allow = '.0123456789';//string the allowed chars:
var matches,element = e.target || e.srcElement;
if (String.fromCharCode(key).length === 0)
{
return e;
}
if (allow.indexOf(String.fromCharCode(key)) === 0)
{//dot
element.value = element.value.replace(/[0-9]+$/,function(group)
{
return ('000' + group).substr(-3);
});
return e;
}
if (allow.indexOf(String.fromCharCode(key)) > -1)
{
matches = (element.value.replace(/\./g) + String.fromCharCode(key)).match(/[0-9]{1,3}/g);
if (+(matches[matches.length -1]) <= 255)
{
element.value = matches.join('.');
}
}
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}?
Now this code still needs a lotof work, this is just to get you going, and hopefully encourage you to look into the event object, how JS event handlers work and all the rest. BTW, since you're new to JS, this site is worth a bookmark
现在这段代码仍然需要大量的工作,这只是为了让你继续前进,并希望鼓励你研究事件对象,JS 事件处理程序如何工作以及所有其他的。顺便说一句,既然你是 JS 新手,这个网站值得收藏