1

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?

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
Martin at Mennt
  • 5,677
  • 13
  • 61
  • 89

1 Answers1

2

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; }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Okay, thought it was something like that. My problem is that I inherit from `DefaultModel` on `Registration`, and as far as I know I cant inherit from more than one class. How can I solve that? – Martin at Mennt Sep 21 '11 at 17:25
  • @Martin, you can inherit from a single class but you can implement as many interfaces as you like. `IValidatableObject` is an interface. – Darin Dimitrov Sep 21 '11 at 17:25
  • Will this work even if I use it with a private sealed class that I put my data annotations? Reason being it was a database first. – Vyache May 14 '14 at 20:55