Validating primitive types in ASP.NET MVC

Posted by Alex on Stack Overflow See other posts from Stack Overflow or by Alex
Published on 2010-05-29T20:39:00Z Indexed on 2010/05/29 20:42 UTC
Read the original article Hit count: 184

Filed under:

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?

© Stack Overflow or respective owner

Related posts about asp.net-mvc