Conditional validation

Conditional validation

Old forum URL:

kiddo85 posted on Wednesday, February 22, 2012


I have a hard time trying to implement conditional validation with CSLA for MVC. 

I have a class Customer that I want to validate. If the Customer is of type 'Person' then First and Last names are required and if it's a Company then 'Company name' is required. I have the following code:

public class Customer : BusinessBase<Customer>, ISavable


public CustomerTypes Type...;

public string FirstName...;

public string LastName...;

public string CompanyName...;

protected override void AddBusinessRules()




            BusinessRules.RuleSet = "Person";

            BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(FirstNameProperty));

            BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(LastNameProperty));


            BusinessRules.RuleSet = "Company";

            BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CompanyNameProperty));


            BusinessRules.RuleSet = "default";



object ISavable.Save(bool forceUpdate)


            BusinessRules.RuleSet = this.Type.ToString();



            if (this.IsValid)


                //DO STH WHEN VALID


            BusinessRules.RuleSet = "default";

            return this;




I have an MVC application where I enter new customer and when I enter invalid data validation is going ok, i.e. the object is invalid (at least debugging shows so) but nothing is shown on the MVC page, no validation text that tells me that for example Company Name is missing. How do I do that?

JonnyBee replied on Wednesday, February 22, 2012

Use the Csla.Web.Mvc.CslaModelBinder.

See samples download for how to use this class in you ASP.NET MVC Application.

You can also create Gateway rules that act as "if" statements in the rule engine. Se the RuleTutorial sample.
Or even just subclass the Required rule and implement the if inside the Execute method.

For objects with many rules I find this to be a better approach than Ruleset.



Copyright (c) Marimer LLC