So I'm using ASP.NET MVC RC1 and using the DefaultModelBinder's validation to show validation errors when not-null integer fields are not set to a value. This is done by default by MVC. However the same is not true for string(varchar) fields, because the binder is passed an empty string from the view, which is completely valid for a not-null varchar column.
In practice however when I mark a column as not-null, I pretty much always mean I want it to be non-empty. So I've come up with this way of adding that validation check to the default binder:
public class DefaultEntityBinder : DefaultModelBinder
{
protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
bool valid = base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
ColumnAttribute column = propertyDescriptor.Attributes.OfType<ColumnAttribute>().FirstOrDefault();
if (column != null &&
propertyDescriptor.PropertyType == typeof(string) &&
!column.CanBeNull &&
value.IsNullOrBlankString())
{
valid = false;
bindingContext.ModelState[propertyDescriptor.Name].Errors.Add("A value is required");
}
return valid;
}
}
I'm wondering if this is the most efficient way of achieving the goal of adding required string field validation to the default validation in MVC.