Skip to content

Instantly share code, notes, and snippets.

@alfredoem
Last active April 21, 2016 16:02
Show Gist options
  • Select an option

  • Save alfredoem/9dd2c743c1b58064a051fdd28f2ffc81 to your computer and use it in GitHub Desktop.

Select an option

Save alfredoem/9dd2c743c1b58064a051fdd28f2ffc81 to your computer and use it in GitHub Desktop.
Input only numbers
$(document).on('propertychange input keypress', '.mask-regex', function(e) {
let valueChanged = false;
let self = $(this);
if (e.type=='propertychange') {
valueChanged = e.originalEvent.propertyName=='value';
} else {
valueChanged = true;
}
if (valueChanged) {
let regex = self.data('mask-regex');
let defaultValue = self.attr('defaultValue') ? self.attr('defaultValue') : '';
if (regex) {
regex = new RegExp(regex, 'g');
if(e.type == 'input') {
if (is.empty(defaultValue) && regex.test(self.val()) === false) {
self.val('');
} else {
self.next().addClass('active');
}
self.attr('defaultValue', self.val());
} else {
let key = (document.all) ? e.keyCode : e.which;
let k = String.fromCharCode(key);
if (key === 46 || key <= 13) {
return true;
}
return regex.test(k);
}
} else {
console.log(' =( You must define the regular expression in attribute data-mask-regex of the input =)');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment