Last active
August 29, 2015 13:56
-
-
Save Knovour/9285961 to your computer and use it in GitHub Desktop.
Be sure that user input is number or number array ex: '2,4,6,1'
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
// Be sure that user input is number or number array ex: '2,4,6,1' | |
// Demo: | |
// http://jsfiddle.net/ED2Ra/6/ | |
// http://codepen.io/Knovour/pen/fFJxi | |
var keyRegex = /[\d,]$/; | |
var numberArrayReg = /^((0$|0,)|[1-9]\d*,?)*$/; // (0$|0,) : prevent 00 or 0[1-9] | |
$('input[type=text]') | |
.keypress(function(event) { | |
var key = String.fromCharCode(event.which); | |
if(!keyRegex.test(key) || (!$(this).val() && key === ',')) // If input value is emtpy, can't input ',' | |
return false; | |
}).on('keyup paste', function(event) { | |
var value = $(this).val(); | |
if(!numberArrayReg.test(value)) { | |
value = value | |
.replace(/,{2,}/i, ',') // remove multi ',' sign | |
.replace(/^,+/i, '') // remove ',' sign at start, ex: ',1,2,3' | |
.replace(/[^\d,]/ig, '') // remove not number char & ',' sign | |
.replace(/(^|,)0+(\d+)/ig, "$1$2"); // remove multi zero, ex: '001,003' => '1,3'; | |
$(this).val(value); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment