Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom Validation Attribute with Custom Model Binder in MVC 2
    primarykey
    data
    text
    <p>I apologise for the amount of code I have included. I've tried to keep it to a minimum.</p> <p>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.</p> <p>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.</p> <p>Validation Attribute;</p> <pre><code>public class IsPhoneNumberAttribute : ValidationAttribute { public override bool IsValid(object value) { //do some checking on 'value' here return true; } } </code></pre> <p>Useage of the attribute in my model;</p> <pre><code> [Required(ErrorMessage = "Please provide a contact number")] [IsPhoneNumberAttribute(ErrorMessage = "Not a valid phone number")] public string Phone { get; set; } </code></pre> <p>Custom Model Binder;</p> <pre><code>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 &gt; 10) bindingContext.ModelState.AddModelError("Phone", "Phone is too long."); } } </code></pre> <p>Global asax;</p> <pre><code>System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] = new CustomContactUsBinder(); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload