Tag Archives: Validation

Custom Model Binders and Request Validation

In ASP.NET MVC you can create your own model binders to control the way that models are constructed from an HTTP request. For example, if you don’t want any whitespace characters in your model, you can create a custom model binder that trims all whitespace characters when constructing  a model object. You only have to implement the IModelBinder interface and its BindModel method in a class and register it during application startup.

Getting the value from the HTTP request

There are many examples online of how to build a custom model binder. In all these examples you can find a common way of getting a value from the HTTP request:

public class MyModelBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult != null)
        {
            var theValue = valueProviderResult.AttemptedValue;

            // etc...
        }
    }
}

The code above works nicely and you get protection for potential dangerous request values out of the box. Now let’s assume that we want some potential dangerous values like HTML or XML tags in our model. The recommended way is to add an [AllowHtml] attribute to the model property that may contain HTML and no validation happens for that property. Alternatively, it’s possible to add an [ValidateInput(false)] attribute to the controller action that accepts the model with HTML content, but this turns off validation for all model properties.

A potentially dangerous Request.Form value was detected from the client

Wait a minute! Didn’t we just explicitly say to allow those dangerous values? What’s happening?

It appears that a call to bindingContext.ValueProvider.GetValue() in the code above always validates the data, regardless any attributes. Digging into the ASP.NET MVC sources revealed that the DefaultModelBinder first checks  if request validation is required and then calls the bindingContext.UnvalidatedValueProvider.GetValue() method with a parameter that indicates if validation is required or not.

Unfortunately we can’t use any of the framework code because it’s sealed, private or whatever to protect ignorant devs from doing dangerous stuff, but  it’s not too difficult to create a working custom model binder that respects the AllowHtml and ValidateInput attributes:

public class MyModelBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // First check if request validation is required
        var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest && bindingContext.ModelMetadata.RequestValidationEnabled;

        // Get value
        var valueProviderResult = bindingContext.GetValueFromValueProvider(shouldPerformRequestValidation);
        if (valueProviderResult != null)
        {
            var theValue = valueProviderResult.AttemptedValue;

            // etc...
        }
    }
}

The other required piece is a way to retrieve an unvalidated value. In this example we use an extension method for the ModelBindingContext class:

public static ValueProviderResult GetValueFromValueProvider(this ModelBindingContext bindingContext, bool performRequestValidation)
{
    var unvalidatedValueProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;
    return (unvalidatedValueProvider != null)
               ? unvalidatedValueProvider.GetValue(bindingContext.ModelName, !performRequestValidation)
               : bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
}

Validation in ASP.NET MVC – part 4: example with server-side and client-side validation

This is part 4 of a series of posts. See also:

In the previous posts, I described how we implemented model-based validation on the server-side in Cuyahoga with ASP.NET MVC and as the icing on the cake, we also added some client-side validation (also model-based).

Now, everything can be found in the Cuyahoga SVN sources but I have to agree that it can be a daunting task to check out the complete sources and find all pieces of the validation puzzle. Therefore, I’ve created a little sample application with everything from the previous posts combined.

validation-sample-app

Hopefully, this will make things a little bit clearer. You can download the sample app here. Visual Studio 2008 and ASP.NET MVC Beta are required.

Enjoy!

Validation in ASP.NET MVC – part 3: client-side validation with jquery validation

This is part 3 of a series of posts. See also:

In the first two parts, I showed how you can perform validation on the server side with Castle Validation attributes and extend that model with custom validation logic. With this, we have everything we need to properly validate our model.

For a better user experience though, it would also be nice that we could re-use (part of) our validation logic on the client-side. Luckily, lots of others have already looked into this and the only thing I had to do was to throw everything together and stir it a little bit :) .

The ingredients are:

How it works

client-side-validation-1

  1. The client-side validation is called via an HtmlHelper extension method ClientSideValidation:
    <%= Html.ClientSideValidation(ViewData.Model, “my_form_id”)%>;
  2. The HtmlHelper extension requests an instance of a BrowserValidationEngine that returns the client script for validation;
  3. BrowserValidationEngine has a reference to an IValidatorRegistry instance that returns all (Castle) validators for the given model;
  4. For each validator, the referenced IBrowserValidatorProvider generates the appropriate client script;
  5. Finally, all generated client script code is combined and sent to the browser in a single javascript block.

The existing Monorail codebase proved to be of great value and could be used almost seamlessly. The only difference is the way the client code is generated. Originally, the validators generated css class attributes for the Monorail form helpers, but we don’t have those with ASP.NET MVC, so all client code is generated as jQuery validation rules.

Below, you can see the output of the validation helper for the new user form in Cuyahoga:

<script type="text/javascript">
$(document).ready(function() {
    jQuery.validator.addMethod('notEqualTo', function(value, element, param) { return value != jQuery(param).val(); }, 'Must not be equal to {0}.' );
    jQuery.validator.addMethod('greaterThan', function(value, element, param) { return ( IsNaN( value ) && IsNaN( jQuery(param).val() ) ) || ( value > jQuery(param).val() ); }, 'Must be greater than {0}.' );
    jQuery.validator.addMethod('lesserThan', function(value, element, param) { return ( IsNaN( value ) && IsNaN( jQuery(param).val() ) ) || ( value < jQuery(param).val() ); }, 'Must be lesser than {0}.' );
    jQuery.validator.addMethod('numberNative', function(value, element, param) { return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:\,\d+)?$/.test(value); }, 'Not a valid number.' );
    jQuery.validator.addMethod('simpleDate', function(value, element, param) { return this.optional(element) || /^\d{1,2}\-\d{1,2}\-\d{4}$/.test(value); }, 'Not a valid date.' );
    $("#userform").validate({
        rules : {
            UserName: {  rangelength: [1, 50] , required: true },
            Password: {   required: true , rangelength: [5, 50] , equalTo: "#PasswordConfirmation" },
            PasswordConfirmation: {   equalTo: "#Password" , rangelength: [5, 50] , required: true },
            FirstName: { rangelength: [1, 100] },
            LastName: { rangelength: [1, 100] },
            Email: {   required: true , rangelength: [1, 100] , email: true },
            Website: { rangelength: [1, 100] }
        },
        messages : {
            UserName: {  rangelength: "The username must be between 1 and 50 characters" , required: "The username may not be empty" },
            Password: {   required: "The password may not be empty" , rangelength: "The password must contain at least 5 characters" , equalTo: "The password must be the same as the confirmation password" },
            PasswordConfirmation: {   equalTo: "The password must be the same as the confirmation password" , rangelength: "The password must contain at least 5 characters" , required: "The password confirmation may not be empty" },
            FirstName: { rangelength: "The firstname must be between 1 and 100 characters" },
            LastName: { rangelength: "The lastname must be between 1 and 100 characters" },
            Email: {   required: "E-mail address may not be empty" , rangelength: "E-mail address must be between 1 and 100 characters" , email: "Invalid e-mail address" },
            Website: { rangelength: "The website url must be between 1 and 100 characters" }
        }
    });
});
</script>

which results in this:

client-side-validation-2

Summarizing validation

In this series of posts, I showed how we deal with validation in Cuyahoga and ASP.NET MVC. Personally, I think the nicest part of it is that we have our validation rules centralized and we only have to add one line of code to the view to enable client-side validation.

The code can be found in Cuyahoga SVN and more specifically in the validation sections and the ASP.NET MVC manager. I’ll try to make a standalone sample project with all the validation stuff somewhere in the near future.

Validation in ASP.NET MVC – part 2: custom server-side validation

This is a post in a series of posts. See also:

In the first post of this series, I showed how you can perform basic server-side validation on your model with help of the Castle Validator component. To summarize this post: the controller validates an object that is decorated with validation attributes with the help of an IModelValidator component and adds errors to the ModelState.

The first reason to abstract the validator was to prevent coupling of MVC controllers to the Castle Validators. But the abstraction also provides a very nice extension point. We can inject any kind of validator into the controller constructor as long as it implements the IModelValidator interface:

public LoginController(IAuthenticationService authenticationService, IModelValidator<LoginViewData> modelValidator)
{
    this._authenticationService = authenticationService;
    this.ModelValidator = modelValidator;
}

In the example above, the constructor requires an IModelValidator<LoginViewData> instance. In our case, Castle Windsor injects a CastleModelValidator<LoginViewData> instance that is registered in the container for IModelValidator<T>. We’re already seeing the first extension: the IModelValidator interface has a generic inheritor.

Extending the ModelValidator

In many scenario’s, property validation with the generic CastleModelValidator<T> will suffice, but sometimes you’ll need some extra validation. For example, when creating a new user, we want to check if the username doesn’t already exist. To perform this check, we created a UserModelValidator class that inherits CastleModelValidator<T>.

validation-custom

The CastleModelValidator<T> calls a virtual method PerformValidation() while validating via IsValid(). In UserModelValidator, this method is overriden and performs the check if the username is unique:

public class UserModelValidator : CastleModelValidator<User>
{
    private readonly IUserService _userService;

    public UserModelValidator(IUserService userService)
    {
        _userService = userService;
    }

    protected override void PerformValidation(User objectToValidate, ICollection<string> includeProperties)
    {
        // First validate the property values via the Castle validator.
        base.PerformValidation(objectToValidate, includeProperties);

        // Check username uniqueness.
        if (ShouldValidateProperty("UserName", includeProperties)
            && ! String.IsNullOrEmpty(objectToValidate.UserName))
        {
            if (this._userService.FindUsersByUsername(objectToValidate.UserName).Count > 0)
            {
                AddError("UserName", "UserNameValidatorNotUnique", true);
            }
        }
    }
}

Because the modelvalidators are registered in the Windsor Container, we can inject any kind of service or data access component into the validator and thus making it very easy to perform custom validation logic that needs to check the database, or check an external web service.

Tying things together

We want the UsersController to use the custom UserModelValidator when ValidateModel() is called. All we have to do is to add UserModelValidator to the constructor of the controller and we’re done:

public UsersController(IUserService userService, UserModelValidator userModelValidator)
{
    this._userService = userService;
    this.ModelValidator = userModelValidator;
}

Finally, this is how it looks in the browser. Nice to see the custom validation error nicely integrated with the rest of the errors.

image

Other extension possibilities

In this post we’ve seen an example where we extended our CastleModelValidator<T> to perform custom logic by calling another service. You might as well call a method on the object itself that is validated to perform custom business logic:

protected override void PerformValidation(MyClass objectToValidate, ICollection<string> includeProperties)
{
    base.PerformValidation(objectToValidate, includeProperties);

    if (! objectToValidate.CheckThatMyBizarreBusinessRuleIsValid())
    {
        AddError("MyProperty", "The object to validate is invalid.");
    }
}

You can also opt for plugging in a completely different library. CSLA fans can very easily implement their own version of IModelValidator<T>, or you could write an IModelValidator<T> implementation that uses the Validation Application Block from Enterprise Library.

The code

This is a series of posts that is directly inspired by Cuyahoga development. All code can be found in the Cuyahoga SVN trunk at https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk. The validation stuff sits in the Validation subdirectory of Cuyahoga.Core: https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Core/Validation. Note that Cuyahoga is work in progress. It’s not guaranteed that the code in SVN will be exactly the same as the sample code in this post.

Validation in ASP.NET MVC – part 1: basic server-side validation

Almost every single application has to deal with validating user input. With web applications, you can choose to do the validation on the client side or on the server side. In my opinion, validation should at least take place on the server side and optionally on the client side to improve the user experience. Therefore, I’m starting this series of posts with the basic needs: server-side validation.
For some background, also check the excellent post about validation by Steve Sanderson.

Validate the model and not the UI

In the past I used the ASP.NET WebForms validators. These do a proper job, but are also very much tied to the individual pages, so you have the validation logic scattered all over the place. For Cuyahoga 2, I really wanted a better solution where validation logic is centralized in the model (and removed from the UI layer).
There are already several solutions that make this possible. Microsoft PnP released the validation application block and recently (.NET 3.5 SP1), we have the DataAnnotations from ASP.NET Dynamic Data.

In Cuyahoga, we’re using the Castle Validator component to perform basic validation, mostly because we’re already using other components from the Castle stack and it just works fine. With Castle validators, you’re decorating properties of your Domain entities with attributes like:

[ValidateNonEmpty("UserNameValidatorNonEmpty")]
[ValidateLength(1, 50, "UserNameValidatorLength")]
public virtual string UserName
{
    get { return this._userName; }
    set { this._userName = value; }
}

Note that it’s also possible to decorate DTO’s or presentation models or whatever you want to call these data containers. In Cuyahoga for example, we have a LoginViewData class that is only used in the UI layer, that is also decorated with validator attributes. If we have a validation infrastructure we might as well (ab)use it :) .

IModelValidator

So how are we going to use the Castle validators with ASP.NET MVC?

First we have to make a decision where we want to validate the model. You can do this in the controller or in the service layer (if you one). Some people suggest doing validation in the data access layer but I think the responsibility of a data access layer is persisting and retrieving the model and nothing else.

I’ve chosen to validate the model from the controller because it’s a little bit more convenient as you don’t have to throw exceptions across layers and translate those exceptions to error messages for the user. For validation, all controllers inherit from a base controller that has a ValidateModel() method. This controller also has an instance of an IModelValidator interface to perform the actual validation, so we don’t pollute the controller too much with validation logic and also prevent coupling to a specific implementation.

validation-controller

At this point, the controller can validate, but to use the Castle validators we have to implement IModelValidator and pass that to the controller. But first: a base controller doesn’t know which type to validate, but a concrete controller does (assuming we’re only validating one concrete type in a controller) and therefore we created the IModelValidator<T> interface. The CastleModelValidator<T> class implements this interface.

Because we’re using the Castle Windsor IoC container we can wire everything together in the controller constructor:

public class LoginController : BaseController
{
    private readonly IAuthenticationService _authenticationService;
    /// <summary>
    /// Create and initialize an instance of the LoginController class.
    /// </summary>
    /// <param name="authenticationService">The authentication service</param>
    /// <param name="modelValidator">The IModelValidator for LoginViewData</param>
    public LoginController(IAuthenticationService authenticationService, IModelValidator<LoginViewData> modelValidator)
    {
        this._authenticationService = authenticationService;
        this.ModelValidator = modelValidator;
    }
}

In the container is the registered that when asked for an instance of IModelValidator<T>, the container should return an instance of CastleModelValidator<T>. The constructor in the code above, receives an instance of CastleModelValidator<LoginViewData>and sets the ModelValidator of the base controller.

How it works: the login screen

The Login action of the LoginController performs validation after populating a LoginViewData instance via TryUpdateModel():

public ActionResult Login(string returnUrl)
{
    var loginUser = new LoginViewData();
    try
    {
        if (TryUpdateModel(loginUser) && ValidateModel(loginUser))
        {
             // do authentication and exception handling

ValidateModel() automatically adds all errors to the ASP.NET MVC ModelState, so we have to do very little to actually display the validation errors:

login

The code

This is a series of posts that is directly inspired by Cuyahoga development. All code can be found in the Cuyahoga SVN trunk at https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk. Please note that all ASP.NET MVC stuff sits in the Manager subdirectory of the Cuyahoga.Web: https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Web/Manager.