Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is how I have done it:</p> <p>1)override GetValidators() in a cusotm implementation of DataAnnotationsModelValidatorProvider . Here you can read your file and decide on which validators to attach to the property being looked at.</p> <p>2) write you're own ValidationAttributes and override the IsValid() method to implement the custom rules you want. You can also override FormatErrorMessage to format the error message any way you want to. You can even have those propagated to the client side by implementing IClientValidatable in your ValidationAttributes.</p> <p>3) Register the provider in Application_Start() in Global.asax with</p> <pre><code>ModelValidatorProviders.Providers.Add(new VProvider()); </code></pre> <p>The custom implementation of DataAnnotationsModelValidatorProvider can be something like this:</p> <pre><code>protected override IEnumerable&lt;ModelValidator&gt; GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable&lt;Attribute&gt; attributes) { IEnumerable&lt;ModelValidator&gt; toRet = new Collection&lt;ModelValidator&gt;(); string prop = metadata.PropertyName; //get the custom rules you want applied from database or file or any other storage AddImplicitRequiredAttributeForValueTypes = false; //to remove implicit required from value types if you want to //Determine what attributes you want to apply to this property attributes = new List&lt;Attribute&gt;() { new MyCustomAttribute() }; //Ask the base class to construct the list of validators to return to the caller return = base.GetValidators(metadata, context, attributes); } </code></pre> <p>the custom attribute would look something like:</p> <pre><code>public class MyCustomAttribute:ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { //perform whatever tests you want here and return true/false } public override string FormatErrorMessage(string name) { //do some formatting } public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var r = new ModelClientValidationRule { ErrorMessage = "Some error message", ValidationType = "customType", }; r.ValidationParameters.Add(paramName,paramValue); yield return r; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload