Restrict users such that they will not copy or cut and paste a “Negative” number in a textbox from other textbox ASP.NET

核能气质少年 提交于 2020-01-16 10:14:00

问题


I have the following code to allow only one negative symbol and also negative numbers.

But my user did a testing and said she can copy/cut -ve values from one textbox to another. Ideally, they shouldn't be allowed to copy/cut and paste a negative number from a textbox to aother textbox, but, if the number is positive, then allow them to cut/copy and paste.

I have to do this only in Javascript as I already have validation function on keypress event for textbox in JS. I use a hidden field for getting values from server side on when to do my logic.

function numbersOnly(Sender,evt,isFloat,isNegative) {
        if(Sender.readOnly) return false;       

        var key   = evt.which || !window.event ? evt.which : event.keyCode;
        var value = Sender.value;

        console.log(key);

         if (value[0] != '-' && key != 45) return false;
          if (value[0] == '-' && key == 45) return false;

        if((key == 46 || key == 44) && isFloat){   
            var selected = document.selection ? document.selection.createRange().text : "";
            if(selected.length === 0 && value.indexOf(".") == -1 && value.length > 0) Sender.value += ".";
            return false;
        }
        if(key == 45) { // minus sign '-'
            if(!isNegative) return false;
            if(value.indexOf('-')== -1) Sender.value = '-'+value; else Sender.value = value.substring(1);
            if(Sender.onchange != null) {
                if(Sender.fireEvent){
                    Sender.fireEvent('onchange');
                } else {
                    var e = document.createEvent('HTMLEvents');
                        e.initEvent('change', false, false);
                    Sender.dispatchEvent(e);
                }
            }

            var begin = Sender.value.indexOf('-') > -1 ? 1 : 0;
            if(Sender.setSelectionRange){
                Sender.setSelectionRange(begin,Sender.value.length);
            } else {
                var range = Sender.createTextRange();
                range.moveStart('character',begin);
                range.select();                 
            }

            return false;
        }
        if(key > 31 && (key < 48 || key > 57)) return false;
    }

Any help would be appreciated to modify the above function for restricting a number to be copied or cut and past if it is negative.

来源:https://stackoverflow.com/questions/27743496/restrict-users-such-that-they-will-not-copy-or-cut-and-paste-a-negative-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!