Skip to content

Instantly share code, notes, and snippets.

@SyntaxC4
Created December 31, 2012 08:22
Show Gist options
  • Select an option

  • Save SyntaxC4/4418269 to your computer and use it in GitHub Desktop.

Select an option

Save SyntaxC4/4418269 to your computer and use it in GitHub Desktop.
using System;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class ValidationExtensions
{
public static MvcHtmlString ValidationMessageLabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string errorClass = "error")
{
string elementName = ExpressionHelper.GetExpressionText(expression);
MvcHtmlString normal = html.ValidationMessageFor(expression);
if (normal != null)
{
string newValidator = Regex.Replace(normal.ToHtmlString(), @"<span([^>]*)>([^<]*)</span>", string.Format("<label for=\\"{0}\\" $1>$2</label>", elementName), RegexOptions.IgnoreCase);
if (!string.IsNullOrWhiteSpace(errorClass))
newValidator = newValidator.Replace("field-validation-error", errorClass);
return MvcHtmlString.Create(newValidator);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment