Adding client-side validation to custom Editor Templates in MVC

When an editor template is overridden with custom one you lose automatic scaffolding of client-side validation which uses data annotation rules. In such a case they should be added manually to your templates.

In the beginning of HTML form you should add  @Html.ValidationSummary(true). The parameter excludePropertyErrors = true because I don’t want to mix up error for properties with other model errors.

@using (Html.BeginForm("SignIn", "Auth", FormMethod.Post, new {@class = "form-signin"}))
    <h4>Sign In</h4>
    <button type="submit" class="btn btn-lg btn-primary btn-block">Sign In</button>
    <button type="button" class="btn btn-xs btn-default btn-block">Sign Up</button>
    <button type="button" class="btn btn-xs btn-default btn-block">Forget password?</button>

For each property in your HTML markup you should add special extension @Html.ValidationMessageFor(…)

<label for="inputEmail" class="sr-only"></label>
<input type="email" id="inputEmail" name="@Html.NameFor(m => m.Email)" class="form-control" placeholder="Email" required autofocus value="@Html.ValueFor(m=> m.Email)">
@Html.ValidationMessageFor(m => m.Email)



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Post

%d bloggers like this: