Created
April 13, 2016 06:41
-
-
Save ineo6/63d4ea907d042c706bd692c7c09e8574 to your computer and use it in GitHub Desktop.
jquery input number validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.fn.numeral = function() { | |
this.bind("keydown", | |
function(e) { | |
// Allow: backspace, delete, tab, escape and enter | |
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 || | |
// Allow: Ctrl+A, Command+A | |
(e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) || | |
// Allow: home, end, left, right, down, up | |
(e.keyCode >= 35 && e.keyCode <= 40)) { | |
// let it happen, don't do anything | |
return; | |
} | |
// Ensure that it is a number and stop the keypress | |
if ((e.shiftKey || (e.keyCode < 48 || (e.keyCode > 57 && e.keyCode != 189 && e.keyCode != 190))) && (e.keyCode < 96 || e.keyCode > 105)) { | |
e.preventDefault(); | |
} | |
// 如果使用者輸入-,先判斷現在的值有沒有-,如果有,就不允許輸入 | |
if (e.keyCode == 189 && /-/g.test(this.value)) { | |
e.preventDefault(); | |
} | |
// 如果使用者輸入.,先判斷現在的值有沒有.,如果有,就不允許輸入 | |
if (e.keyCode == 190 && /\./g.test(this.value)) { | |
e.preventDefault(); | |
} | |
}); | |
this.bind("keyup", | |
function() { | |
if (/[^0-9\.-]/g.test(this.value)) { | |
this.value = this.value.replace(/[^0-9\.-]/g, ''); | |
} | |
if (/-/g.test(this.value) && !/^-/g.test(this.value)) { | |
this.value = this.value.replace(/-/g, ''); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment