Nick Riggs, Web Developer

Making stuff up about web development since last week.

6 February 2012

Subscribe to our RSS feed

Posted in ASP.NETFoolproof March 22, 2010

“MVC Foolproof Validation” is my first open source project to help bridge the gap in ASP.NET MVC Data Annotations when dealing with contingent or dependent scenarios

I like performing validation using Data Annotations in ASP.NET MVC. However, with complex scenarios, I find myself having to choose a different path. One complex scenario is “contingent scenario” also called “dependent scenario”:

Check out this simple class to demonstrate a contingent validation problem.

private class Person
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public bool Married { get; set; }
    public string MaidenName { get; set; }
}

Let’s say our validation rule is: “If the user selects Married=true, then the user must also provide a MaidenName”.

Data Annotations, currently, don’t handle validating this rule.  And, I can’t make a custom class-level annotation because that will only validate the model and not the individual item.

What I would like to write is:

[Required]
public bool Married { get; set; }

[RequiredIfTrue("Married")]
public string MaidenName { get; set; }

This simple yet unsupported markup fueled a couple of late night hack-a-thons.   Now, I am pleased to announce the fruits of my labor… my first opensource project: “MVC Foolproof Validation

http://foolproof.codeplex.com/

MVC Foolproof Validation extends the Data Annotation validation provided in ASP.NET MVC. Initial efforts are focused on contingent validation.

Some examples of what is possible:

public class SignUpViewModel
{
    [Required]
    public string Password { get; set; }

    [EqualTo("Password", ErrorMessage="Passwords do not match.")]
    public string RetypePassword { get; set; }
}
public class EventViewModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    public DateTime Start { get; set; }

    [Required]
    [GreaterThan("Start")]
    public DateTime End { get; set; }
}

Status of the project:
It’s in development, but it works.
Client validation is supported, both standard MVC and jQuery flavors.

Download the source, take a look and make suggestions. I feel strongly that Foolproof is something the community could really use. I hope to roll out a first release in a couple of weeks.

http://foolproof.codeplex.com/