Validating primitive types in ASP.NET MVC
- by Alex
I've implemented the following classes to validate data
public abstract class Validated
{
public bool IsValid { get { return (GetRuleViolations().Count() == 0); } }
public abstract IEnumerable<RuleViolation> GetRuleViolations();
}
public partial class User: Validated
{
public override IEnumerable<RuleViolation> GetRuleViolations()
{
if (this.Age < 1)
yield return new RuleViolation("Age can't be less than 1");
}
}
It works great! When the form is submitted I just do
if (user.IsValid == false) blah...
But I still need to validate that the Age is an integer
int a = 0;
if (!int.TryParse(age, out a))
{
error = "Not integer";
// ...
}
How can I move this to my model?