问题
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