Skip to content

Instantly share code, notes, and snippets.

@juanvgarcia
Last active January 2, 2016 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanvgarcia/8231823 to your computer and use it in GitHub Desktop.
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.
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