Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Render error messages of Backbone.Validation for Twitter Bootstrap

View backbone-validation-bootstrap.js.coffee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
_.extend Backbone.Validation.callbacks,
valid: (view, attr, selector) ->
control = view.$('[' + selector + '=' + attr + ']')
group = control.parents(".control-group")
group.removeClass("error")
 
if control.data("error-style") == "tooltip"
# CAUTION: calling tooltip("hide") on an uninitialized tooltip
# causes bootstraps tooltips to crash somehow...
control.tooltip "hide" if control.data("tooltip")
else if control.data("error-style") == "inline"
group.find(".help-inline.error-message").remove()
else
group.find(".help-block.error-message").remove()
 
invalid: (view, attr, error, selector) ->
control = view.$('[' + selector + '=' + attr + ']')
group = control.parents(".control-group")
group.addClass("error")
 
if control.data("error-style") == "tooltip"
position = control.data("tooltip-position") || "right"
control.tooltip
placement: position
trigger: "manual"
title: error
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")
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")
target.text(error)
kcivey commented

In place of $(view.el).find() you can use just view.$().

Owner

edited, thanks ;)

Note: If your fields aren't being set silently, "invalid" fields are still valid on the model. This means your error messages will be cleared by the "valid" callback as soon as you touch another field. This is easily fixed if you drop the following into the valid callback prior to any work being done:

    # If the input field is still in an invalid state, don't remove error
    if view.model.preValidate(attr, control.val())
      return

(Thanks for the very helpful gist.)

Thanks for the very useful gist.

This can be extended to work with backbone-deep-model, which uses '.' characters as path separators, by quoting the attributes in the control selector in both the valid and invalid sections as follows:

control = view.$('[' + selector + '=' + attr + ']')

becomes

 control = view.$('[' + selector + '="' + attr + '"]')

Same as above in plain JavaScript, possibly will be useful for someone like me who writes in plain JavaScript but still searches for rendering Backbone.Validation messages for Twitter Bootstrap forms

_.extend(Backbone.Validation.callbacks, {
  valid: function(view, attr, selector) {
    var control, group;
    control = view.$('[' + selector + '=' + attr + ']');
    group = control.parents(".control-group");
    group.removeClass("error");
    if (control.data("error-style") === "tooltip") {
      if (control.data("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(".control-group");
    group.addClass("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);
    }
  }
});

Thanks for the code @webdevbyjoss

This should work fine with bootstrap 3

_.extend Backbone.Validation.callbacks,
  valid: (view, attr, selector) ->
    control = view.$('[' + selector + '=' + attr + ']')
    group = control.parents('.form-group')
    group.removeClass('has-error')

    if control.data('error-style') == 'tooltip'
      # CAUTION: calling tooltip('hide') on an uninitialized tooltip
      # causes bootstraps tooltips to crash somehow...
      control.tooltip 'hide' if control.data('tooltip')
    else if control.data('error-style') == 'inline'
      group.find('.help-inline.error-message').remove()
    else
      group.find('.help-block.error-message').remove()

  invalid: (view, attr, error, selector) ->
    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
      control.tooltip 'show'
    else if control.data('error-style') == 'inline'
      if group.find('.help-inline').length == 0
        group.find('.form-control').after('<span class=\'help-inline error-message\'></span>')
      target = group.find('.help-inline')
      target.text(error)
    else
      if group.find('.help-block').length == 0
        group.find('.form-control').after('<p class=\'help-block error-message\'></p>')
      target = group.find('.help-block')
      target.text(error)
AVVS commented

LN #3 and LN#17

control = view.$('[' + selector + '=' + attr + ']')

to

control = view.$('[' + selector + '="' + attr + '"]')

it would allow for complex selectors

If you are going to have input fields names like this,

...
    <input name="clients[address][street]" type="text" >
...

The following code should work well.

_.extend(Validation.callbacks, {
    valid: function(view, attr, selector) {
        // compose the attr - for complex situations
        var arr = attr.split('.'),
            el = '';
        for (var i = 0; i < arr.length; i++) {
            if (i === 0) el += arr[i];
            else el += '[' + arr[i] + ']';
        }

        var control, group;
        control = view.$('[' + selector + '="' + el + '"]');
        group = control.parents(".control-group");
        group.removeClass("error");

        if (control.data("error-style") === "tooltip") {
            if (control.data("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) {
        // compose the attr - for complex situations
        var arr = attr.split('.'),
            el = '';
        for (var i = 0; i < arr.length; i++) {
            if (i === 0) el += arr[i];
            else el += '[' + arr[i] + ']';
        }

        var control, group, position, target;
        control = view.$('[' + selector + '="' + el + '"]');
        group = control.parents(".control-group");
        group.addClass("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);
        }
    }
});

So I hate to be that guy but, @driehle, could you add a license to this gist?

We are actually using this gist in production for exactly what it's written for - binding Backbone.Validation to twitter bootstrap. It works like a charm. However, the lawyers recently reviewed our code and turned up this gist not having a license. Sigh.

Also not sure if you're aware of this but the Backbone.Validation FAQ actually links directly to this gist: http://thedersen.com/projects/backbone-validation/#faq/how-can-i-use-it-with-twitter-bootstrap. Perhaps there's an opportunity here to promote this gist to its own full-fledged project and get that FAQ updated?

Ping @driehle.

(Sorry to be a pest; I blame The Laywers.)

This is getting enough attention that it feels like it should become a proper github project with issues and pull requests, and maybe an organization with multiple committers to maintain it...

Agreed with @brycefisher :+1:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.