asp.net-mvcasp.net-mvc-3model-validationivalidatableobject

IValidatableObject not triggered


I'm trying to make use of the IValidatableObject as described here http://davidhayden.com/blog/dave/archive/2010/12/31/ASPNETMVC3ValidationIValidatableObject.aspx.

But it just wont fire when I'm trying to validate, the ModelState.IsValid is always true.

Here is my model code:

[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : DefaultModel
{
    [Editable(false)]
    [Display(Name = "Property one")]
    public int PropertyOne { get; set; }
}

public class RegistrationMetaData :IValidatableObject
{
    [Required(ErrorMessage = "Customer no. is required.")]
    [Display(Name = "Customer no.")]
    public string CustomerNo { get; set; }

    [Display(Name = "Comments")]
    public string Comments { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (new AccountModel().GetProfile(CustomerNo) == null)
            yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
    }
}

I extend a LINQ to SQL table called Registration, my first guess was that this is not possible to do on a Meta class, but I'm not sure?

I do not get any errors, and it builds just fine, but the Validate method will not fire. What have I missed?


Solution

  • That's because it is the Registration model that should implement IValidatableObject and not RegistrationMetaData:

    [MetadataType(typeof(RegistrationMetaData))]
    public partial class Registration : IValidatableObject
    {
        [Editable(false)]
        [Display(Name = "Property one")]
        public int PropertyOne { get; set; }
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (new AccountModel().GetProfile(CustomerNo) == null)
                yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
        }
    }
    
    public class RegistrationMetaData
    {
        [Required(ErrorMessage = "Customer no. is required.")]
        [Display(Name = "Customer no.")]
        public string CustomerNo { get; set; }
    
        [Display(Name = "Comments")]
        public string Comments { get; set; }
    }