views:

365

answers:

1

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.

+1  A: 

I have looked through the default model binding (in particular, TypeHelpers.TypeAllowsNullValue), and I don't see anything better for this. You could implement IDataErrorInfo on the type which contains the string, but you would have to do that on each type you support. So what you're doing is fine. If you're open to third-party code, the xVal validation framework is worth considering. Then you can use things like the attributes in System.ComponentModel to decorate non-nullable strings.

Craig Stuntz