Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validator.TryValidateProperty Not Working

I am trying to implement Validator.TryValidateProperty and even though there is a [Required] DataAnnotation, the TryValidateProperty returns a valid response.

Here is my Customer partial class:

[MetadataType(typeof(Customer.Metadata))]
public partial class Customer : global::System.Data.Objects.DataClasses.EntityObject 
{
   ...
private sealed class Metadata
    {

        [Required]
        [SSNValidAttribute(ErrorMessage = "The SSN should be 9 numeric characters without any punctuation.")]
        [DisplayName("SSN")]
        public String SSN { get; set; }
...

And here is the code that is returning True:

...
var customer = new Customer();
            customer.SSN = "";
            var vc = new ValidationContext(customer, null, null);
            vc.MemberName = "SSN";
            var res = new List<ValidationResult>();
            var result = Validator.TryValidateProperty(customer.SSN, vc, res);
...
like image 376
hangtendesign Avatar asked Jun 14 '11 20:06

hangtendesign


1 Answers

Ok, just found the solution for dealing with the sealed MetadataType class.

var customer = new Customer();
TypeDescriptor.AddProviderTransparent
(new AssociatedMetadataTypeTypeDescriptionProvider
    (customer.GetType()), customer.GetType());
customer.SSN = "";
var vc = new ValidationContext(customer, null, null);
vc.MemberName = "SSN";
var res = new List<ValidationResult>();
var result = Validator.TryValidateProperty(customer.SSN, vc, res);

I had to add the following:

TypeDescriptor.AddProviderTransparent
(new AssociatedMetadataTypeTypeDescriptionProvider
    (customer.GetType()), customer.GetType());

Found solution at this address: http://forums.silverlight.net/forums/p/149264/333396.aspx

like image 135
hangtendesign Avatar answered Nov 20 '22 02:11

hangtendesign