Skip to content

Instantly share code, notes, and snippets.

@jacopotarantino
Created January 5, 2016 20:41
Show Gist options
  • Save jacopotarantino/8face4efdb51cbb73cc1 to your computer and use it in GitHub Desktop.
Save jacopotarantino/8face4efdb51cbb73cc1 to your computer and use it in GitHub Desktop.
Formats phone number inputs
(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