Note that there are some explanatory texts on larger screens.

plurals
  1. POvalidating child properties of model using DataAnnotations or CustomValidation
    text
    copied!<p>i'm working on a MVC3 webapp and my Model consist of many classes that use a custom type for textual properties. for example my Product entity looks like :</p> <pre><code>public class Product { public int ProductId {get;set;} public TextRef Title {get;set;} public TextRef Description {get;set;} } </code></pre> <p>and TextRef is :</p> <pre><code>public class TextRef { public int LangId {get;set;} public string Text {get;set;} } </code></pre> <p>so in my views i'm using :</p> <pre><code>@Html.EditorFor(model =&gt; model.Title.Text) @Html.ValidationMessageFor(model =&gt; model.Title.Text) </code></pre> <p>is there a way to enable validation for these TextRef properties using DataAnnotations ?</p> <p>i didn't find any, so i have created a custom validator attribute:</p> <pre><code>public class TextRefRequiredAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { if (value is TextRef) return !string.IsNullOrEmpty(((TextRef)value).Text); else return true; } public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule(); rule.ValidationType = "textref"; yield return rule; } } </code></pre> <p>now the server-side validation is working but client-side isn't. in fact the "data-val-" attributes didn't generated for their inputs.</p> <p><strong>UPDATE:</strong></p> <p>my client script is : </p> <pre><code>$.validator.addMethod("textref", function (value, element, param) { return (value != ""); }); $.validator.unobtrusive.adapters.addBool("textref"); </code></pre> <p>i also tried using FluentValidation:</p> <pre><code>public class CategoryValidator : AbstractValidator&lt;CategoryViewModel&gt; { public CategoryValidator() { RuleFor(o =&gt; o.Title.Text) .NotEmpty(); } } </code></pre> <p>but still no chance.</p> <p>thanks</p>
 

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