Validation does not work when I use Validator.TryValidateObject

前端 未结 4 1634
盖世英雄少女心
盖世英雄少女心 2020-11-30 07:56

DataAnnotations does not work with buddy class. The following code always validate true. Why ?

var isValid = Validator.TryValidateObject(new Customer(), Context, res

4条回答
  •  难免孤独
    2020-11-30 09:00

    After some research I couldn't find any reason why TryValidateObject always return true if I use MetadataType (buddy class). But it works with the following code (xVal).

        public static IEnumerable GetErrors(object instance, string name)
        {
            var metadataAttrib = instance.GetType()
                    .GetCustomAttributes(typeof(MetadataTypeAttribute), true)
                    .OfType().FirstOrDefault();
            var buddyClassOrModelClass = metadataAttrib != null
                    ? metadataAttrib.MetadataClassType
                    : instance.GetType();
            var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass)
                .Cast();
            var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType())
                .Cast();
    
            var list = from buddyProp in buddyClassProperties
                       join modelProp in modelClassProperties on
                                buddyProp.Name equals modelProp.Name
                       from attribute in buddyProp.Attributes.OfType()
                       where !attribute.IsValid(modelProp.GetValue(instance))
                       select new ErrorInfo(
                           buddyProp.Name,
                           attribute.FormatErrorMessage(modelProp.Name),
                           instance);
    
            if (name != null)
                list = list.Where(x => x.PropertyName == name);
    
            return list;
        }
    

提交回复
热议问题