2

Is there a way in ASP.NET MVC3 to customize the result of the Html.ValidationMessageFor(...) method? For example add an image next to the error text or similar... But I want to be able to change the image whether the validation is successful or not...

2 Answers 2

11

You can see that the error is wrapped with a Css Class, all you need to do is use that Css Class at your own will.

The default MVC3 contains in the styles.css

/* Styles for validation helpers
-----------------------------------------------------------*/
.field-validation-error
{
    color: #ff0000;
}

.field-validation-valid
{
    display: none;
}

.input-validation-error
{
    border: 1px solid #ff0000;
    background-color: #ffeeee;
}

.validation-summary-errors
{
    font-weight: bold;
    color: #ff0000;
}

.validation-summary-valid
{
    display: none;
}

just add your images there.

Sign up to request clarification or add additional context in comments.

Comments

7

Yup U can write ur own extension to do so

public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        TagBuilder div = new TagBuilder("div");
        div.AddCssClass("aside");

        string modelName = ExpressionHelper.GetExpressionText(expression);
        ModelState state = htmlHelper.ViewData.ModelState[modelName];
        if (state != null)
            if ((state.Errors != null) && (state.Errors.Count > 0))
                div.AddCssClass("invalid");
            else 
                div.AddCssClass("valid");

        div.InnerHtml = htmlHelper.ValidationMessageFor(expression).ToString();
        return MvcHtmlString.Create(div.ToString());
    }

Then use something like this

@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name) 

And lastly u need to define ur css for invalid and aside class to customize how the error looks.

4 Comments

Unfortunatly this was not what I need. I can't find a way to use this to display different images depending on whether the validation succeeded or not (like a check and an X icon)...
@nogola : sure u can...just add the required style on the class invalid you can also modify the code to add a different class when there is no error...as shown in the edit above
Also...i have just used an example of div..u can use anything else that u want to show next to the form editor
No, because this extension method is only called on page load to set up the initial html. After that all validation is done through the jquery-validate-plugin and no server code is called...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.