2011/06/16

How ASP.NET MVC 3 custom validation works

Here I show how validation works. There are many useless parameters in this example. They were created with the aim of watching where information comes from and where they go to.

Create a ValidationAttribute for server side validation and for generating client instructions

public class MyValidationAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return value.ToString() == "I AM VALID";
    }

    public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "myparameterizedvalidationtype",
            ValidationParameters = { { "firstparam", 10 }, { "secondparam", new { Amount = 108, Message = "Hello" } } }
        };
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "myunparameterizedvalidationtype"
        };
    }
}


Use that attribute in model
public class MyViewModel
{
    [MyValidation(ErrorMessage = "This is the error message")]
    public string Name { get; set; }
}

This simple Razor view creates a form with validation rules

@model MyWebSite.MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/myvalidation.js")" type="text/javascript"></script>


@using (Html.BeginForm()) {
    @Html.ValidationSummary(false, "Errors found. Correct them.")
    @Html.EditorForModel()
    <input type="submit" value="Register" />
}

This is how the model property is rendered



myvalidation.js - Check comments

// we add a custom jquery validation method
jQuery.validator.addMethod('testIamValid', function (value, element, params) {
    /*
        element: HTMLInputElement
        params: Object
            anything: "aaa"
            anythingelse: "bbb"
        value: "Value typed on text input"
    */
    return value == "I AM VALID";
}, '');

// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('myparameterizedvalidationtype', ["firstparam", "secondparam"], function (options) {
    /*
        options: Object
            element: HTMLInputElement
            form: HTMLFormElement
            message: "This is the error message"
            messages: Object
            params: Object
                firstparam: "10"
                secondparam: "{ Amount = 108, Message = Hello }"
            rules: Object
    */
    //This causes testIamValid method to be called.
    options.rules['testIamValid'] = { anything: "aaa", anythingelse: "bbb" };
    //Message that will be shown if testIamValid method return false
    options.messages['testIamValid'] = options.message;
});

No comments:

Post a Comment