Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Validation add class to containing div

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

like image 531
williamsandonz Avatar asked Aug 18 '12 00:08

williamsandonz


2 Answers

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();
  }
}
like image 129
williamsandonz Avatar answered Oct 22 '22 09:10

williamsandonz


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.

like image 5
Max Toro Avatar answered Oct 22 '22 09:10

Max Toro