Home > MonoRail > MonoRail and Castle Validator

MonoRail and Castle Validator

Recently I have been working to add validation to a web application I am building using MonoRail. A bit of research turned up a brilliant component created by Hammett that greatly simplifies adding client and server side validation in one place.

Hammett’s validation components work within the scope of the databinding operation that allows you to bind form fields directly into parameters in a reasonably seamless manner. You do need to be able to apply validation attributes to properties in the object being bound, so it does not appear that you can validate simple parameters, but I am using a presentation model for a majority of my forms so this was not a problem.

There is a great guide here and Hammett’s screencast here that show you how to set up the validation.

There are a couple of gotchas with the validation though, and these repeatedly tripped me up until I understood what was going on, so I will publish them here and hope that it helps someone else (all of these problems appear when doing server side validation only – I have deliberately disabled the client side validation until the server side validation is complete and correct):

Validation of simple properties happens before the value has been converted. This means the validator gets passed a string value and therefore does not always behave as expected. For example ValidateNotSameValue(CallResult.Unspecified) passes validation when a value of Unspecified is submitted because it compares Unspecified (the enum value) with “Unspecified” (a string value). My solution at the moment is to write type specific validators that extend ValidateNotSameValueAttribute and convert the value to a string that is passed to the validator (like this NotSameEnumValueValidator).

Validation only occurs if a value for the field is sent in the request. If no value is set, then the validation for that property is not triggered. For example I have a property called QuestionnaireId which must not be empty, this rule is enforced using a custom validator that ensures the value is a Guid and is not equal to Guid.Empty. The validator works (it is used in a number of other places), however it will not ensure a value is selected from a radio button group as no value is posted to the server for that form field (the databinder explicitly skips validation if there is no value to bind). I have not worked out a strategy for dealing with this yet.

I think Hammett has done a great job, and this component covers the basic scenarios as well as providing a good extensibility mechanism, however there are a few gotchas (even Hammett outlines a few here), the key is to be aware of what is happening and why.


Categories: MonoRail
  1. No comments yet.
  1. No trackbacks yet.