Created
January 5, 2016 20:41
-
-
Save jacopotarantino/8face4efdb51cbb73cc1 to your computer and use it in GitHub Desktop.
Formats phone number inputs
This file contains 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 () { | |
$('#format-me').on('keydown', function (event) { | |
var text = event.target.value | |
var regex = /^\(\d{3}\)\s\d{3}-\d{4}$/ | |
// if it's valid do nothing | |
if (regex.test(text)) { return } | |
// strip the input down to numbers only | |
text = text.replace(/\D/g, '') | |
// if someone hits backspace just return | |
if (event.keyCode === 8) { | |
event.preventDefault() | |
text = text.slice(0, -1) | |
} | |
// `(${ text.slice(0,3) }) ${ text.slice(3,6) }-${ text.slice(6,10) }` | |
// format the text | |
var parsed = '' | |
if (text.length > 0) {parsed += `(${ text.slice(0,3) }`} | |
if (text.length > 2) { parsed += `) ` } | |
parsed += text.slice(3,6) | |
if (text.length > 5) { parsed += `-` } | |
parsed += text.slice(6,10) | |
event.target.value = parsed | |
}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment