I have a MVC website with a complex model. I'm using xVal to do my validation by decorating my model properties with validation attributtes.
I'm looking for at way to add a StringLengthRule to all properties of type string without manually adding a StringLengthAttributte to all the properties.
One way to go was to make my own IRulesProvider as shown here:
public class TODO_MyRulesProvider : IRulesProvider
{
public RuleSet GetRulesFromType(Type type)
{
Dictionary<string,Rule> myRules = new Dictionary<string, Rule>();
foreach (var property in type.GetProperties())
{
if(property.PropertyType == typeof(string))
{
var rule = new StringLengthRule(0, 255);
myRules[property.Name] = rule;
}
}
ILookup<string, Rule> rules = myRules.ToLookup(o => o.Key, o => o.Value);
return new RuleSet(rules);
}
}
protected void Application_Start()
{
xVal.ActiveRuleProviders.Providers.Add(new TODO_MyRulesProvider());
}
With this approach I can get it to work, but the method GetRulesFromType is called once per property, which gives med json code like this in the html:
{"RuleName":"Custom","RuleParameters":{"Function":"RegExValidate","Parameters":"{\"regEx\":\"^\\\\w+$\"}"}},
{"RuleName":"StringLength","RuleParameters":{"MinLength":"0","MaxLength":"255"}},
{"RuleName":"StringLength","RuleParameters":{"MinLength":"0","MaxLength":"255"}},
{"RuleName":"StringLength","RuleParameters":{"MinLength":"0","MaxLength":"255"}},
{"RuleName":"StringLength","RuleParameters":{"MinLength":"0","MaxLength":"255"}},
{"RuleName":"StringLength","RuleParameters":{"MinLength":"0","MaxLength":"255"}}
How can I accomplish my goal?