5

I'm using bootstrap CSS form styles, When a textbox gets a validation error message, I need to put the class "error" on the containg . How can I do this?

Problem is, all the validations fire on ajax before submitting the form, except for my custom validators which only fire on post. So need to make sure it happens 4 both scenarios.

http://twitter.github.com/bootstrap/base-css.html#forms

williamsandonz
  • 15,864
  • 23
  • 100
  • 186

3 Answers3

8

Inside the onError function in jquery.validate.unobtrusive, just add the .addClass("error") line like this:

function onError(error, inputElement) {  // 'this' is the form element
  var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
      replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

  container.removeClass("field-validation-valid").addClass("field-validation-error");
  error.data("unobtrusiveContainer", container);
  container.parents(".field-encapsulator:first").addClass("error");

  if (replace) {
    container.empty();
    error.removeClass("input-validation-error").appendTo(container);
  }
  else {
    error.hide();
  }
}
KyleMit
  • 30,350
  • 66
  • 462
  • 664
williamsandonz
  • 15,864
  • 23
  • 100
  • 186
5

ASP.NET MVC adds the field-validation-error class to the error message element, and input-validation-error to form controls, both on the server-side and client-side via javascript. There's no containing element, depending on your code the form control and its label may or may not be under the same containing element. And, even if they do, MVC will set the mentioned classes to the form control and error message element and not the containing element.

Also, when you autogenerate a form using Html.EditorForModel() the generated markup is like this:

<div class="editor-label"><label for="foo">Foo</label></div>
<div class="editor-field"><input name="foo"/></div>

There's no containing element that could map to the control-group class on Twitter Bootstrap. You could change this template by adding an EditorTemplates/Object.cshtml template.

I'd suggest you adapt Twitter Bootstrap to ASP.NET MVC and not the other way around.

Max Toro
  • 28,282
  • 11
  • 76
  • 114
1

As described in some of the answers at How to add a 'submitHandler' function when using jQuery Unobtrusive Validation?, the settings can be accessed by $("form").data("validator").settings.

And you can then set any valid/invalid class you like:

var settings = $("form").data("validator").settings;
settings.errorClass += " is-invalid";
settings.validClass += " is-valid";
Magnus
  • 11
  • 3