Skip to content

Instantly share code, notes, and snippets.

@Knovour
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Knovour/9285961 to your computer and use it in GitHub Desktop.
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'
// 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