Last active
April 21, 2016 16:02
-
-
Save alfredoem/9dd2c743c1b58064a051fdd28f2ffc81 to your computer and use it in GitHub Desktop.
Input only numbers
This file contains hidden or 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
| $(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