I am working on mvc3 application, i have created a custom validationMessage to validate a simple field. This custom validationMessage only show an div with title and message instead of the default span, i have this :
@Html.ValidationMessageCustomFor(model => model.FirstName)
This is the code to my custom validation:
public static MvcHtmlString ValidationCustomFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
string propertyName = ExpressionHelper.GetExpressionText(expression);
string name = helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName));
if (helper.ViewData.ModelState[name] == null ||
helper.ViewData.ModelState[name].Errors == null ||
helper.ViewData.ModelState[name].Errors.Count == 0)
{
return MvcHtmlString.Empty;
}
StringBuilder htmlValidation = new StringBuilder();
htmlValidation.AppendLine("<div>");
htmlValidation.AppendLine("<table>");
htmlValidation.AppendLine("<tr>");
htmlValidation.AppendLine("<td><img src='/Content/Imgages/Error.jpg'></td>");
htmlValidation.AppendLine("</tr>");
htmlValidation.AppendLine("<tr>");
htmlValidation.AppendFormat("<td>{0}</td>", name);
htmlValidation.AppendLine("</tr>");
htmlValidation.AppendLine("<tr>");
htmlValidation.AppendFormat("<td>{0}</td>", helper.ViewData.ModelState[name].Errors[0].ErrorMessage);
htmlValidation.AppendLine("</tr>");
htmlValidation.AppendLine("</table>");
htmlValidation.AppendLine("</div>");
return MvcHtmlString.Create(htmlValidation.ToString());
}
This works fine when I use server side validation, but when I active client side validation it doesn't work.
The default Html.ValidationMessageFor yes works fine with client side validation, but my custom Html.ValidationMessageCustomFor doesn't work.
Could you please help me, any ideas?
I modified my custom helper, I added the "data-valmsg-for" atrib for the span, it is the code :
public static MvcHtmlString ValidationCustomFor2<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
string propertyName = ExpressionHelper.GetExpressionText(expression);
string name = helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName));
if (helper.ViewData.ModelState[name] == null ||
helper.ViewData.ModelState[name].Errors == null ||
helper.ViewData.ModelState[name].Errors.Count == 0)
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("span");
tag.Attributes.Add("class", "field-validation-error");
tag.Attributes.Add("data-valmsg-for", name);
tag.Attributes.Add("data-valmsg-replace", "true");
var text = tag.ToString(TagRenderMode.StartTag);
text += "<b>My custom html</b>";
text += tag.ToString(TagRenderMode.EndTag);
return MvcHtmlString.Create(text);
}
But it doesn't appear, it looks I should do something from the client side, but I don't know WHAT? Any ideas please?