validation - CustomValidationAttribute doesn't work when other attributes are applied to the class -
reproduction:
imports system.componentmodel imports system.componentmodel.dataannotations module module1 sub main() dim type = gettype(contact) typedescriptor.addprovidertransparent( new associatedmetadatatypetypedescriptionprovider(type), type) dim contact new contact dim context new validationcontext(contact, nothing, nothing) dim errors new list(of validationresult) dim result = validator.tryvalidateobject(contact, context, errors, true) end sub end module <customvalidation(gettype(contact.contactmd), "*********************")> <metadatatype(gettype(contact.contactmd))> public class contact public property email string public property emailrepeat string public class contactmd '<required()> public property email '<required()> public property emailrepeat public shared function validateemails(byval contact contact) _ validationresult return if(contact.email = contact.emailrepeat, validationresult.success, new validationresult("fail!")) end function end class end class
the above code throw exception:
the customvalidationattribute method '*********************' not exist in type 'contactmd' or not public , static.
this exception justified , it's sign things working. once uncomment required
attributes on properties in md class, exception not throw, means, validation system doesn't validate both property-typed attributes , class-level attributes.
any workaround?
the answer is, validation system validates property validation attributes first (the required
attributes in case), , proceed customvalidationattribute
if object passed property attributes.
so per reproduction above, changing line
dim contact new contact
to (allowing enitity pass property validation):
dim contact new contact { .email = "*", .emailrepeat = "*" }
will throw expected exception.
Comments
Post a Comment