简体   繁体   English

JavaScript 只接受 0 到 255 之间的数字

[英]JavaScript to accept only numbers between 0 to 255 range

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.我是 JavaScript 新手,需要一些专家建议来解决我的需求。 Please suggest me请建议我

Thanks Sudhir谢谢苏迪尔

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 所指出的,您正在对allownums(this.value)事件而不是输入值执行验证,因此将 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 (eg in an IP address).但是,阅读其他答案,显然您正在寻找验证八位字节(例如在 IP 地址中)。 If so, please state that in the question, as it passed me by today.如果是这样,请在问题中说明这一点,因为它今天通过了我。 For an octet:对于八位字节:

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.请注意现在使用 onkeydown 的更改,以便我们可以捕获无效的按键操作并完全防止值更改。 If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";如果必须清除输入,则执行if(!validateIPKeyPress(event)) this.value = ""; . .

I would rather go instantly for validation of whole ip address.我宁愿立即去验证整个 IP 地址。 Allowing input both numbers and dots, parsing them thru REGEX pattern.允许输入数字和点,通过 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/

Single Integer单整数

You can use the following solution to check if the user input for a single integer is 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 address is 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" />

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)

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/

Update更新
I've set up a fiddle that 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我已经设置了一个 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 .首先也是最重要的一点是,并非所有浏览器都在事件对象上设置了keycode属性 You're better off passing the entire event object to the function, and deal with X-browser issues there.您最好将整个事件对象传递给函数,并在那里处理 X 浏览器问题。
Secondly, you're checking key after key, but at no point are you checking the actual value 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:还有一些东西,比如使用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 lot of 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.现在这段代码仍然需要大量的工作,这只是为了让你继续前进,并希望鼓励你研究事件对象、JS 事件处理程序如何工作以及其他所有内容。 BTW, since you're new to JS, this site is worth a bookmark顺便说一句,既然你是 JS 新手,这个网站值得收藏

    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>

I've seen many answers that have overlooked two important factors that may fail to validate range number on keypress:我看到很多答案都忽略了可能无法验证按键范围数的两个重要因素:

  1. When the value in input textbox is NOT SELECTED , the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key) .当输入文本框中的值不是 SELECTED 时,真正的结果应该是(input.value * 10) + parseInt(e.key)而不是简单的input.value + parseInt(e.key) It should be * 10 because you add one more digit at the back during keypress, eg 10 becomes 109 .它应该是* 10因为您在按键过程中在后面再添加一位数字,例如10变为109
  2. When the value in input textbox IS SELECTED , you can simply check if Number.isInteger(parseInt(e.key)) because when 255 is selected, pressing 9 will not turn into 2559 but 9 instead. When the value in input textbox IS SELECTED , you can simply check if Number.isInteger(parseInt(e.key)) because when 255 is selected, pressing 9 will not turn into 2559 but 9 instead.

So first of all, write a simple function that check if the input value is selected by the user:所以首先,编写一个简单的函数来检查用户是否选择了输入值:

function isTextSelected (input) {
    if (!input instanceof HTMLInputElement) {
        throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
    };
    return document.getSelection().toString() != "" && input === document.activeElement;
}

Next, this will be your on keypress event handler that takes into consideration of the above two factors:接下来,这将是您的 on keypress 事件处理程序,它考虑了上述两个因素:

$("input[type='number']").on("keypress", function (e) {
     if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255 
         && !isTextSelected($(this)[0]))) {
         e.preventDefault();
     };
});

Take note of this condition within another brackets, it is one whole condition by itself:请注意另一个括号中的此条件,它本身就是一个完整的条件:

(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))

For the < 0 condition, you don't even need it here because the negative sign (-) will be automatically prevented as the sign itself is not an integer .对于< 0条件,这里甚至不需要它,因为负号(-)将被自动阻止,因为符号本身不是整数

KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29 and press 1 , which will become 129 .已知问题:但是,上述解决方案并没有解决用户将光标移动到29起始位置并按下1 ,该位置将变为129 This is because 29 * 10 = 290 , which already exceed 255 , preventing user from entering 129 , which is valid.这是因为29 * 10 = 290已经超过255 ,阻止用户输入129 ,这是有效的。 The start position is particularly hard to track when the input type="number" .当输入type="number"时,起始位置特别难以跟踪。 But it should be enough to resolve the normal way of input for an integer range field.但它应该足以解决整数范围字段的正常输入方式。 Any other better solutions are welcome.欢迎任何其他更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM