Conditional validation

Print Friendly, PDF & Email

◷ Reading Time: 2 minutes

Introduction

When you define a rule model it is easy to implement rules that always require validation. However, in a complex system, rules do not need to always be applicable. Sometimes these need to be part of the validation only under specific circumstances. You may need to exclude or include them based on some other logic.

Rules

Assume we have a Person entity that has both Age and Email properties. We are going to write two validation rules:

  1. Person’s email address must NOT be null or empty
  2. An adult person (age greater or equal to 18) must NOT provide an empty or null email address

These two validation rules are similar, the only difference is that we do not want to run the Email validation if the person is not an Adult (age>18)

Completed rule

<Validation name="PersonValidation">
 
  <Declaration>
    <Using path="System.DateTime"/>
  </Declaration>
  <!--
    Rule: Adult (age>=18) MUST provide email address when registering
    HasEmail     IsAdult       Result
    T            T             T
    T            F             T
    F            T             F
    F            F             T
    -->
 
  <Logic name="check email using False">
    <False message="Adult must have an email">
      <When>
        <And>
          <Check value= "(DateTime.Today.Year - Birthday.Year) >= 18"/>
          <Validate logic="EmptyOrNull" value="Email" />
        </And>
      </When>
    </False>
  </Logic>
 
  <Logic name="EmptyOrNull" variable="$input">
    <Or>
      <Null value="$input"/>
      <Empty value="$input"/>
    </Or>
  </Logic>
 
</Validation>

Next sections

In the next couple of articles, we will cover different aspects of modeling and executing the validation rules using Validation logic.

  1. Introduction to validation rules
  2. Validating hierarchy (Inheritance relation)
  3. Validating association (Aggregation, Composition)
  4. Validation rule execution and collecting results
  5. Pass extra input values to validation rules
  6. Extending validation conditions and actions
  7. How to apply rules under some conditions
  8. Referencing commonly used logic
  9. Sample for Order processing validation logic
Updated on July 8, 2019

Was this article helpful?

Related Articles