Custom Validation Attribute with Custom Model Binder in MVC 2

Posted by griegs on Stack Overflow See other posts from Stack Overflow or by griegs
Published on 2010-06-18T04:26:32Z Indexed on 2010/06/18 4:33 UTC
Read the original article Hit count: 412

I apologise for the amount of code I have included. I've tried to keep it to a minimum.

I'm trying to have a Custom Validator Attribute on my model as well as a Custom Model binder. The Attribute and the Binder work great seperately but if I have both, then the Validation Attribute no longer works.

Here is my code snipped for readability. If I leave out the code in global.asax the custom validation fires but not if I have the custom binder enabled.

Validation Attribute;

public class IsPhoneNumberAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        //do some checking on 'value' here
        return true;
    }
}

Useage of the attribute in my model;

    [Required(ErrorMessage = "Please provide a contact number")]
    [IsPhoneNumberAttribute(ErrorMessage = "Not a valid phone number")]
    public string Phone { get; set; }

Custom Model Binder;

public class CustomContactUsBinder : DefaultModelBinder
{
    protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ContactFormViewModel contactFormViewModel = bindingContext.Model as ContactFormViewModel;

        if (!String.IsNullOrEmpty(contactFormViewModel.Phone))
            if (contactFormViewModel.Phone.Length > 10)
                bindingContext.ModelState.AddModelError("Phone", "Phone is too long.");
    }
}

Global asax;

System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] = 
  new CustomContactUsBinder();

© Stack Overflow or respective owner

Related posts about asp.net-mvc-2

Related posts about custom-validators