Using rules to validate data in your application

Using Business validation rules in your code is a simple process. First, load a RuleSet using one of the overloaded FromXml static methods. There are methods to load from a file, from a stream, or a string (FromXmlString method).

C#
RuleSet ruleSet = RuleSet.FromXml("C:\rules.ruleset")

Visual Basic
Dim ruleSet As RuleSet = RuleSet.FromXml("C:\rules.ruleset")

Next, create a IDictionary to hold the data being validated. Add the entities to the IDictionary, using the string keys that are expected for that entity by any DataValues in the rules.

C#
IDictionary entities = new Hashtable();
entities.Add("Account", myAccountInstance);

Visual Basic
Dim entities As IDictionary = New Hashtable()
entities.Add("Account", myAccountInstance)

You can now call Evaluate which will return a boolean indicating if the data is valid or invalid, or you can call EvaluateBrokeRules which will return a collection of rules that are violated by the data. If the data is valid this method will return an empty (Count = 0) collection.

C#
bool result = ruleSet.Evaluate(entities);
IList brokenRules = ruleSet.EvaluateBrokenRules(entities);

Visual Basic
Dim result As Boolean = ruleSet.Evaluate(entities)
Dim brokenRules As IList = ruleSet.EvaluateBrokenRules(entities)

If you want to display the broken rules to the user you can use the rule.Messager and rule.MessageText. The Message is used to evaluate the MessageText whenever a rule is broken. Whenever evaluating a rule returns false, the Message is automatically evaluated and the result stored in the MessageText property, so you can display the message to the user without having to evaluate it.

C#
string message = "";
foreach(ValidationRule rule in brokenRules) {
      message += rule.MessageText;
      message += "\n";
}
MessageBox.Show(message);

Visual Basic
Dim message As String
For Each rule As ValidationRule In brokenRules
      message += rule.MessageText
      message += vbCrLf
Next
MessageBox.Show(message)


You can also evaluate the rule message by itself if you need to for any reason:

C#
string message = "";
foreach(ValidationRule rule in brokenRules) {
      message += rule.Message.Evaluate(ruleSet.CreateContext());
      message += "\n";
}
MessageBox.Show(message);

Visual Basic
Dim message As String
For Each rule As ValidationRule In brokenRules
      message += rule.Message.Evaluate(ruleSet.CreateContext)
      message += vbCrLf
Next
MessageBox.Show(message)