Exemplo n.º 1
0
        /// <summary>
        /// Validates the specified property of the specified validation source.
        /// </summary>
        /// <param name="validationSource">The validation source.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>The collection of validation mesasges.</returns>
        public static ValidationMessageCollection Validate(this IValidatable validationSource, string propertyName)
        {
            validationSource.CannotBeNull();
            propertyName.CannotBeNullOrEmpty();

            ValidationMessageCollection messages = new ValidationMessageCollection();
            List <string> validationContexts;
            object        propertyValue;

            // get property value
            var properties = ReflectionExtensions.GetProperties(validationSource.GetType());

            if (properties.TryGetValue(propertyName, out PropertyData propertyData))
            {
                if (propertyData.PropertyInfo.CanRead &&
                    propertyData.PropertyInfo.CanWrite)
                {
                    propertyValue = propertyData.PropertyInfo.GetValue(validationSource);

                    // get validation context
                    validationContexts = new List <string>();
                    validationContexts.Add(ValidationContext.Default);                                                     // always add the default validation context
                    validationContexts.AddRange(validationSource.GetActiveValidationContexts() ?? Array.Empty <string>()); // add currently active validation context

                    foreach (var validationContext in validationContexts.Distinct())
                    {
                        messages.AddRange(validationSource.Validate(propertyName, propertyValue, validationContext));
                    }
                }
            }

            return(messages);
        }