Created
May 24, 2012 13:16
-
-
Save mdellavo/2781497 to your computer and use it in GitHub Desktop.
Format phone number/credit card/ssn/etc inputs by regular expression
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
(function() { | |
var formatters = { | |
'phone' : [/^\(?\s?(\d{3})\s?\)?\s?\-?\s?(\d{3})\s?\-?\s?(\d{4})$/, '($1) $2-$3' ], | |
'ssn' : [/^(\d{3})\s?\-?\s?(\d{2})\s?\-?\s?(\d{3})$/, '$1-$2-$3' ], | |
'creditcard' : [/^(\d{4})\s?\-?\s?(\d{4})\s?\-?\s?(\d{4})\s?\-?\s?(\d{4})$/, '$1-$2-$3-$4'] | |
}; | |
jQuery.fn.formatWith = function(regex, replacement) { | |
$(this).change(function() { | |
this.value = this.value.replace(regex, replacement); | |
}).change(); | |
}; | |
jQuery.fn.format = function(formatter) { | |
if(formatter in formatters) | |
jQuery.fn.formatWith.call(this, formatters[formatter][0], formatters[formatter][1]); | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment