Is it possible to use the selfvalidation attribute with my validations located in a metadatatype? I'm using Enterprise Library 5's Validation Application Block.
Metadatatypes with self-validation using validation application block
1.4k views Asked by Scott Williams AtThere are 2 answers
This is currently not supported (out of the box) by VAB. Look for instance at this thread at the EntLib forum. I think the main reason this is not supported is because you can't simply place the [SelfValidation] method on the meta data type and expect this to work. Reason it won't work is because self validation methods will typically validate instance members of the type. The signature of the self validation method does not contain the actual object to validate.
A simple work around is call into the meta data type from the entity. For instance:
[MetadataType(typeof(InvoiceMetaData))]
[HasSelfValidation]
public partial class Invoice
{
public string Name{ get; set; }
public int Price { get; set; }
[SelfValidation]
public void CustomValidate(ValidationResults results)
{
// Call into the meta data class
InvoiceMetaData.Validate(this, results);
}
}
public class InvoiceMetaData
{
[StringLengthValidator(1, 10, Tag = "Name")]
string Name { get; set; }
[RangeValidator(0, RangeBoundaryType.Inclusive, 0,
RangeBoundaryType.Ignore, Tag = "Price")]
int Price { get; set; }
public static void CustomValidate(Invoice instance,
ValidationResults results)
{
results.AddResult(new ValidationResult("ErrorMessage1",
instance, "", "", null));
}
}
This of course isn't a very clean solution. VAB however is very extendable and version 5.0 only got better. If you want you can swap existing AttributeValidationFactory
and replace it with a version that is able to do this. It won't be easy though.
Cheers
As I explained in my other answer, this isn't supported out of the box. However, this can be achieved by hooking into the framework using depedency injection and replace the existing
AttributeValidatorFactory
implementation. I written a post on my weblog on how to do this: Mixing Validation Application Block With DataAnnotation: What About SelfValidation?I hope this helps.