JavaScript to accept only numbers between 0 to 255 range

后端 未结 8 1564
野趣味
野趣味 2021-01-22 13:14

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 ente

8条回答
  •  时光说笑
    2021-01-22 13:40

    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

    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 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:

    
    

    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. BTW, since you're new to JS, this site is worth a bookmark

提交回复
热议问题