Last active
January 2, 2016 01:39
-
-
Save juanvgarcia/8231823 to your computer and use it in GitHub Desktop.
This code will add a "PhoneNumber" custom editor for Backbone Forms. The formatting function was taken from:
https://github.com/groupme/jquery-format-phone/blob/master/src/format_phone_input.js, and you could replace it as needed.
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
Backbone.Form.editors.PhoneNumber = Backbone.Form.editors.Text.extend({ | |
initialize: function(options) { | |
Backbone.Form.editors.Text.prototype.initialize.call(this, options); | |
this.$el.on('keyup', function(e){ | |
var input = $(e.currentTarget); | |
input.val(input.val().replace(/[^\d]/g, '')); | |
var digits = input.val(); | |
if (e.which == 8 && digits.length <= 3) { | |
return; | |
} | |
if (e.ctrlKey || e.shiftKey || e.metaKey) { | |
return; | |
} | |
if (e.which == 8 && digits.length > 3) { | |
input.val(digits.substring(0, digits.length - 1)); | |
input.trigger('keydown'); | |
} | |
if (digits.length < 3) { | |
return digits; | |
} | |
if ((digits.length >= 3 && digits.length <= 6)) { | |
var prefix = digits.substring(0, 3); | |
var rest = digits.substring(3, digits.length); | |
return input.val(prefix + '-' + rest); | |
} | |
if (digits.length > 6 && digits.length <= 10) { | |
var areaCode = digits.substring(0, 3); | |
var prefix = digits.substring(3, 6); | |
var rest = digits.substring(6, digits.length) | |
return input.val('(' + areaCode + ') ' + prefix + '-' + rest); | |
} | |
return; | |
}); | |
}, | |
getValue: function() { | |
if(this.$el.val()){ | |
return this.$el.val().replace(/[\s-\(\)]/g, ""); | |
} | |
}, | |
setValue: function(value){ | |
Backbone.Form.editors.Text.prototype.setValue.call(this, value); | |
this.$el.trigger('keyup'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment