Question

I have an invoice object with the following property definition in it ...

[CustomValidation(typeof(InvoiceValidator), "ValidateInvoiceDate")]
 public DateTime InvoiceDate { get; set; }

When I do a postback in my MVC app I get an invoice object back then do this ...

if(ModelState.IsValid)
{
   SaveInvoice(invoice);
}

My validator looks like this ...

public static class InvoiceValidator
{
   public static ValidationResult ValidateInvoiceDate(DateTime invoiceDate, ValidationContext context)
   {
       // some validation code (omitted)
   }
}

My problem seems to be getting the dam thing to work as at the moment it simply throws an exception:

The CustomValidationAttribute method 'ValidateInvoiceDate' does not exist in type 'InvoiceValidator' or is not public and static.

This statement is clearly not right, the validator class exists and so does the method with the right modifiers (public, static). This is code i've used loads before and usually works fine but for some reason this time isn't working.

Any ideas what else might cause this exception to be thrown?

Things i've tried:

clean solution and full rebuild (no errors at compile time). rename the method / validator class and refactor attribute to new values then recompile scratch head ask on here

looks to me like my code isn't being run correctly or something because I can't see why a clearly declared public static method would result in an error saying it's not declared other than that.

Was it helpful?

Solution 2

Ok found it ....

It turns out that this whas wrong:

[CustomValidation(typeof(InvoiceValidator), "ValidateInvoiceDate")]

the "typeof(InvoiceValidator)" whilst it had the right type name it was specific enough and some T4 generated code was generating a type with the same name in a nearer scope so the compiler was matching it to that type.

I'm a bit annoyed by this though ... surely the compiler should have thrown an exception for an ambiguous type reference not a runtime error.

Bad Microsoft !!

OTHER TIPS

ValidateCurrencyCode is your hint. Are you using the InvoiceValidator to validate your CurrencyCode field? It seems like you do use it on other field, but don't have the method implemented in your validator class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top