Skip to content

Instantly share code, notes, and snippets.

@Spinarooni
Last active December 9, 2015 22:29
Show Gist options
  • Save Spinarooni/4338145 to your computer and use it in GitHub Desktop.
Save Spinarooni/4338145 to your computer and use it in GitHub Desktop.
AMD Module for Backbone.Validation Twitter Bootstrap UI Integration
/*
AMD Plugin for Backbone.Validation Twitter Bootstrap UI Integration
Render error messages from Backbone.Validation using Twitter Bootstrap
Adapted from:
https://gist.github.com/2909552#comment-594344
https://gist.github.com/2909552#comment-560252
Updated for Bootstrap 3.
*/
define([
// Libraries
'jquery',
'underscore',
'backbone',
// Plugins
'bootstrap',
'backbone-validation'
],
function($, _, Backbone) {
"use strict";
_.extend(Backbone.Validation.callbacks, {
valid: function(view, attr, selector) {
var control, group;
control = view.$('[' + selector + '=' + attr + ']');
// See if the input field is still in an invalid state so we don't
// remove the error message (Useful when not allowing invalid values
// to be set on the model)
if (view.model.preValidate(attr, control.val())) { return; }
group = control.parents(".form-group");
group.removeClass("has-error");
if (control.data("error-style") === "tooltip") {
if (control.data("bs.tooltip")) {
return control.tooltip("hide");
}
} else if (control.data("error-style") === "inline") {
return group.find(".help-inline.error-message").remove();
} else {
return group.find(".help-block.error-message").remove();
}
},
invalid: function(view, attr, error, selector) {
var control, group, position, target;
control = view.$('[' + selector + '=' + attr + ']');
group = control.parents(".form-group");
group.addClass("has-error");
if (control.data("error-style") === "tooltip") {
position = control.data("tooltip-position") || "right";
control.tooltip({
placement: position,
trigger: "manual",
title: error
});
return control.tooltip("show");
} else if (control.data("error-style") === "inline") {
if (group.find(".help-inline").length === 0) {
group.find(".controls").append("<span class=\"help-inline error-message\"></span>");
}
target = group.find(".help-inline");
return target.text(error);
} else {
if (group.find(".help-block").length === 0) {
group.find(".controls").append("<p class=\"help-block error-message\"></p>");
}
target = group.find(".help-block");
return target.text(error);
}
}
});
return Backbone.Validation;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment