Multiple RuleSet for a single Model Class with complex properties in MVC.

Jun 19, 2013 at 7:48 PM
Edited Jun 19, 2013 at 7:50 PM
I have a Model class which displays 2 different complex properties of same type as follows :-
public class MainClass 
{ 
   public Name CustomerName {get;set;}
   public Name SupplierName  {get;set;}
}

public class Name
{
   public string FirstName {get;set;}
   public string LastName {get;set;}
   public string DateOfBirth {get;set;}
   public string ssn {get;set;}
}
I have single MVC view where I display this Main class
@model Model.MainClass
<div>
    <div>
       @Html.EditorFor(m=>m.CustomerName)
       @Html.EditorFor(m=>m.SupplierName)
    </div>
</div>
I need to supply validation as follows; -

For CustomerName I need FirstName, LastName and DateofBirth is required.
For SupplierName, I need FirstName , LastName and SSN is required.

I have validator as follows : -
   public class NameValidator : AbstractValidator<Name>
    {
        public NameValidator()
        {
            RuleSet("Customer", () =>
            {
                SharedNameOnlyRules()
                RuleFor(name => name.DateOfBirth).NotEmpty();               
            });

             RuleSet("Supplier", () =>
            {
                SharedNameOnlyRules()
                RuleFor(name => name.SSN).NotEmpty();               
            });
         }
      void SharedNameOnlyRules()
        {
            RuleFor(name => name.FirstName)
                .Cascade(CascadeMode.StopOnFirstFailure)
                .NotEmpty().Length(1, 20);
            RuleFor(name => name.LastName)
                .Cascade(CascadeMode.StopOnFirstFailure)
                .NotEmpty().Length(1, 20);
        }
}
In My controller Post Action Method I have somehting like this :-
public ActionResult CreateOrder([CustomizeValidator(RuleSet = "Customer")] Order model)
{
    if(ModelState.IsValid)
    {

    }
   else
   { 

    }
}
Now I know that I can pass "Customer" ruleset for m=>m.CustomerName property but what about "Supplier" ruleset for m=>m.SupplierName property.
Coordinator
Jun 20, 2013 at 9:28 AM
Hi

In this case you'd probably be better off not using rulesets, but having two separate validators for the differnet properties.

Jeremy
Jun 21, 2013 at 2:51 PM
Yep, thats what I did ultimately and it works. Thanks for your time.