Nick Riggs, Web Developer

Making stuff up about web development since last week.

7 September 2010

Subscribe to our RSS feed

Posted in ASP.NETFoolproof April 12, 2010

Using Foolproof’s ModelAwareValidationAttribute class, you can create custom model-aware data annotations to solve any complex validation scenario

In the beta version of Foolproof, a new base class called ModelAwareValidationAttribute was added. This class serves as the base class for all Foolproof attributes but it also allows developers to create custom complex validation attributes in situations where access to the model is needed.

Here is an example:

We have a view model meant for creating a new user that has a Department and Role property. However we need to enforce some constraints around which roles a new user can be assigned to based on which department they are a member of. For example, only users that are in the “IT Department” can be in the “Software Developers” role.

Here is our view model:

public class CreateUserViewModel
{
    [Required]
    public string Username { get; set; }

    [Required]
    public string Department { get; set; }

    [Required]
    public string Role { get; set; }
}

Now it’s time to create new data annotation using Foolproof to enforce our business logic:

public class RoleValidInDepartmentAttribute : ModelAwareValidationAttribute
{
    //this is needed to register this attribute with foolproof's validator adapter
    static RoleValidInDepartmentAttribute() { Register.Attribute(typeof(RoleValidInDepartmentAttribute)); }

    public override bool IsValid(object value, object container)
    {
        if (value != null && value.ToString() == "Software Developers")
        {
            //if the role was software developers, we need to make sure the user is in the IT department
            var model = (CreateUserViewModel)container;
            return model.Department == "IT Department";
        }

        //the user wasn't in a constrained role, so just return true
        return true;
    }
}

Now we can use our new attribute in our view model:

[Required]
[RoleValidInDepartment(ErrorMessage="This role isn't valid for the selected department.")]
public string Role { get; set; }

The results look good!

Update: I’ve posted how to create an accompanying client side validator.

Download the latest version of MVC Foolproof Validation