.netvalidationenterprise-library

How to not specify ruleset name when reading from config file?


When I read rules from a configuration file, I do something like this:

IConfigurationSource configurationSource = new FileConfigurationSource("myvalidation.config");
var validator = ValidationFactory.CreateValidator<Salary>(configurationSource);

The config file looks like this:

<ruleset name="Default">
  <properties>
    <property name="Address">
       <validator lowerBound="10" lowerBoundType="Inclusive" upperBound="15"
            upperBoundType="Inclusive" negated="false" messageTemplate=""
            messageTemplateResourceName="" messageTemplateResourceType=""
            tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null"
name="String Length Validator" />
     </property>
  </properties>
</ruleset>

My question is - is there a way to not specify the ruleset name? It's not required for me to specify a ruleset name if I am using the attribute approach and I can validate using:

ValidationResults results = Validation.Validate(salary);

Now when reading from config files, I have to specify the ruleset name. There is no overload of the CreateValidator method that accepts the configuration source without specifying the ruleset name. Also, the xml in the config file requires a name attribute for ruleset


Solution

  • When using attributes, and a Ruleset is not specified in the validator or validation call all rules will be applied that do not have a Ruleset defined or the Ruleset name is empty.

    However with configuration it is slightly different since (as you mention) the name of the Ruleset is required for configuration. What you need to do is to create a Ruleset with a name and then indicate that it is the default Ruleset. To indicate that a Ruleset is the default Ruleset apply the attribute defaultRuleset="MyRule" to the type element in the config.

    When a validator is created with no Ruleset specified then the default Ruleset from configuration will be executed when Validate is called.

    In your example the config would look like:

    <type defaultRuleset="Default" [...] >
      <ruleset name="Default">
        <properties>
          <property name="Address">
             <validator lowerBound="10" lowerBoundType="Inclusive" upperBound="15"
                upperBoundType="Inclusive" negated="false" messageTemplate=""
                messageTemplateResourceName="" messageTemplateResourceType=""
                tag=""   type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator,   Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral,   PublicKeyToken=null"
                name="String Length Validator" />
           </property>
        </properties>
      </ruleset>
    </type>