Skip to content

Instantly share code, notes, and snippets.

@derekgates
Last active December 14, 2015 11:19
Show Gist options
  • Save derekgates/5078080 to your computer and use it in GitHub Desktop.
Save derekgates/5078080 to your computer and use it in GitHub Desktop.
Pieces required to enable MVC client side validation with Bootstrap themes. Assumes you are using the 'control-group' and other elements from the Form examples in the Bootstrap tutorials (form-horizontal only for now).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace System.Web.Mvc.Html
{
public static class TwitterBootstrapHelperExtensions
{
//http://stackoverflow.com/questions/7215477/best-approach-for-extending-unobtrusive-javascript-in-mvc3-to-add-a-style-to-a-d
public static MvcHtmlString BootstrapValidationSummary(this HtmlHelper helper,
bool excludePropertyErrors,
string message)
{
if (helper.ViewData.ModelState.Values.All(v => v.Errors.Count == 0)) return new MvcHtmlString(string.Empty);
string errorsList = "<ul>";
foreach (var error in helper.ViewData.ModelState.Values.Where(v => v.Errors.Count > 0))
{
errorsList += string.Format("<li>{0}</li>", error.Errors.First().ErrorMessage);
}
errorsList += "</ul>";
return new MvcHtmlString(string.Format("<div class=\"alert alert-block alert-error\"><strong>{0}</strong>{1}</div>", message, errorsList));
}
}
}
//http://pknopf.com/blog/twitter-bootstrap-clientside-validation-with-jquery-validation-js
//http://stackoverflow.com/questions/7215477/best-approach-for-extending-unobtrusive-javascript-in-mvc3-to-add-a-style-to-a-d
(function ($) {
$.validator.setDefaults({
highlight: function (element) {
$(element).closest('.control-group').addClass('error');
},
unhighlight: function (element) {
$(element).closest('.control-group').removeClass('error');
}
});
$('span.field-validation-valid, span.field-validation-error').each(function () {
$(this).addClass('help-inline');
});
$('form').submit(function () {
if ($(this).valid()) {
$(this).find('div.control-group').each(function () {
if ($(this).find('span.field-validation-error').length == 0) {
$(this).removeClass('error');
}
});
}
else {
$(this).find('div.control-group').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).addClass('error');
}
});
}
});
$('form').each(function () {
$(this).find('div.control-group').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).addClass('error');
}
});
});
}(jQuery));
@dbloch3643
Copy link

Can we get a code snippet it on how to implement this code? please

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment