Yaron
Yaron

Reputation: 2709

Showing MVC validation error next to the element

I'm using the @Html.ValidationMessageFor helper method for validation but the messages are displayed only when I declare Html.ValidationSummary.
Is there a way to show the error messages next to the elements instead of a Validation summary?

<fieldset>
    <legend>Registration Form</legend>
    <ol>
        <li>
            @Html.LabelFor(m => m.UserName)
            @Html.TextBoxFor(m => m.UserName, new { id = "registerName" })
        </li>
        <li>
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password)
            <div>@Html.ValidationMessageFor(m => m.Password)</div>
        </li>
        <li>
            @Html.LabelFor(m => m.ConfirmPassword)
            @Html.PasswordFor(m => m.ConfirmPassword)
            <div>@Html.ValidationMessageFor(m => m.ConfirmPassword)</div>
        </li>
        <li>
            <input type="submit" value="Sign up" />
        </li>
    </ol>
    @*@Html.ValidationSummary()*@
</fieldset>

Thanks!

Upvotes: 1

Views: 800

Answers (1)

AVenger
AVenger

Reputation: 116

@Yaron,

Looking at your code, it all looks good. You don't need the Validation Summary for the validation to work correctly. But you do need the jQuery libraries included.

If you look at a stock Internet MVC Application, you will see at the bottom of the Login page this code:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

This will access the jqueryval bundle from the BundleConfig file in the App_Start folder. Assuming you have all of these in your application, that block of code should fix your problem.

Upvotes: 2

Related Questions