Note that there are some explanatory texts on larger screens.

plurals
  1. POClient-side custom data annotation validation
    primarykey
    data
    text
    <p>I've create a custom data annotation to do some validation on my view model. The problem is that it doesn't validate on the client-side. Here's my model:</p> <pre><code>public class MemberViewModel { [ScaffoldColumn(false)] public int MemberId { get; set; } [Required(ErrorMessage = "Name is required")] public string Name { get; set; } //My custom data annotation [EnforceTrue(ErrorMessage = "You must agree to the Terms and Conditions")] public bool AgreeTerms { get; set; } } </code></pre> <p>My data annotation validation code:</p> <pre><code>public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable { public EnforceTrueAttribute() { } public override bool IsValid(object value) { return value != null &amp;&amp; (bool)value == true; } public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRule() { ValidationType = "enforcetrue", ErrorMessage = this.ErrorMessageString }; } } </code></pre> <p>My controller method:</p> <pre><code>[HttpPost] public ActionResult Index(MemberViewModel viewModel) { Member member = new Member(); TryUpdateModel(member); if (ModelState.IsValid) { _membersRepository.SaveMember(member); return RedirectToAction("Index", "Home"); } return View(viewModel); // validation error, so redisplay same view } </code></pre> <p>And my view:</p> <pre><code>@using (Html.BeginForm("Index", "Members", FormMethod.Post)) { @Html.HiddenFor(m =&gt; m.MemberId) &lt;div class="editor-label"&gt;@Html.LabelFor(model =&gt; model.Name)&lt;/div&gt; &lt;div class="editor-field"&gt;@Html.TextBoxFor(model =&gt; model.Name)&lt;/div&gt; &lt;div class="editor-field"&gt;@Html.CheckBoxFor(model =&gt; model.AgreeTerms) &lt;label for="AgreeTerms"&gt;I agree to the Terms and Conditions&lt;/label&gt;&lt;/div&gt; &lt;p&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/p&gt; @Html.ValidationSummary() } </code></pre> <p>So all my other error messages get displayed in the validation summary with client-side validation. But for my custom data annotation, the error message doesn't show until the rest of the model is valid, and after you submit the form and page reloads, that's when the error is displayed in the summary.</p> <p>Is there something else I need to do here to get it to show up in the summary with the other errors?</p> <p>I'm using C# and ASP.NET MVC 3</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload