Skip to content

Instantly share code, notes, and snippets.

@sharazghouri
Last active April 1, 2020 05:19
Show Gist options
  • Save sharazghouri/7c785fdd8fc0a159711658aceda90ec1 to your computer and use it in GitHub Desktop.
Save sharazghouri/7c785fdd8fc0a159711658aceda90ec1 to your computer and use it in GitHub Desktop.
Phone number validation in jQuery with masking
//Only integer allowed
jQuery.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
(function($){
$(".contact-us-form #phone").inputFilter(function (value) {
return /^\d*$/.test(value); // Allow digits only, using a RegExp
});
$('.contact-us-form #phone').on( 'keydown focus',function( e){
e.target.value = e.target.value.substr( 0, 10) ;
})
$('.contact-us-form #phone').on( 'keyup blur',function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment