Nick Riggs, Web Developer

Making stuff up about web development since last week.

7 September 2010

Subscribe to our RSS feed

Posted in ASP.NETFoolproofJavaScript June 18, 2010

In a previous post, we built a model-aware validator using Foolproof for ASP.NET MVC. Now, it’s time to create the client side version because posting back sucks.

Weeks ago, I covered how to build custom model-aware validators using Foolproof. A question was asked, “How do I build an accompanying client side validator?”. So today I’ll cover that!

In that post, we built a validator that ensured that new users in the “Software Developers” role were also marked as working in the “IT Department.” In this post, we are going to build upon that example.

First, make sure you are including the necessary client side validation scripts:

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<script src="../../Scripts/MvcFoolproofValidation.js" type="text/javascript"></script>

“RoleValidInDepartmentAttribute” was the name of our attribute, so when we are registering our client validator with the ValidatorRegistry, just drop the “Attribute” part.  In your included script file add the following code:

Sys.Mvc.ValidatorRegistry.validators["RoleValidInDepartment"] = function (rule) {
    return function (value, context) {
    };
};

The returned function has two parameters, “value” and “context”. “Value” holds the value of the field that the validator has been placed on – in this example, “Role”. In order to get the value of Department, we have to figure out the Id of the Department field – Foolproof’s helper function getId() helps us with that:

var dependentProperty = foolproof.getId(context.fieldContext.elements[0], "Department");
var dependentValue = document.getElementById(dependentProperty).value;

Once we have both values, we add the validation logic. Return true if validation passes and use the context parameter to return the error message if it fails. The final code:

Sys.Mvc.ValidatorRegistry.validators["RoleValidInDepartment"] = function (rule) {
    return function (value, context) {
        var dependentProperty = foolproof.getId(context.fieldContext.elements[0], "Department");
        var dependentValue = document.getElementById(dependentProperty).value;

        if (value == "Software Developers") {
            if (dependentValue == "IT Department")
                return true;
            else
                return context.validation.fieldErrorMessage;
        }

        return true;
    };
};

Download MVC Foolproof Validation