1 /* ****************************************************************************
\r
3 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5 * This software is subject to the Microsoft Public License (Ms-PL).
\r
6 * A copy of the license can be found in the license.htm file included
\r
7 * in this distribution.
\r
9 * You must not remove this notice, or any other, from this software.
\r
11 * ***************************************************************************/
\r
13 namespace System.Web.Mvc {
\r
15 using System.Collections.Generic;
\r
16 using System.ComponentModel;
\r
17 using System.ComponentModel.DataAnnotations;
\r
18 using System.Globalization;
\r
20 using System.Web.Mvc.Resources;
\r
22 public abstract class AssociatedValidatorProvider : ModelValidatorProvider {
\r
23 protected virtual ICustomTypeDescriptor GetTypeDescriptor(Type type) {
\r
24 return TypeDescriptorHelper.Get(type);
\r
27 public override sealed IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) {
\r
28 if (metadata == null) {
\r
29 throw new ArgumentNullException("metadata");
\r
31 if (context == null) {
\r
32 throw new ArgumentNullException("context");
\r
35 if (metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName)) {
\r
36 return GetValidatorsForProperty(metadata, context);
\r
39 return GetValidatorsForType(metadata, context);
\r
42 protected abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes);
\r
44 private IEnumerable<ModelValidator> GetValidatorsForProperty(ModelMetadata metadata, ControllerContext context) {
\r
45 ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(metadata.ContainerType);
\r
46 PropertyDescriptor property = typeDescriptor.GetProperties().Find(metadata.PropertyName, true);
\r
47 if (property == null) {
\r
48 throw new ArgumentException(
\r
50 CultureInfo.CurrentCulture,
\r
51 MvcResources.Common_PropertyNotFound,
\r
52 metadata.ContainerType.FullName, metadata.PropertyName),
\r
56 return GetValidators(metadata, context, property.Attributes.OfType<Attribute>());
\r
59 private IEnumerable<ModelValidator> GetValidatorsForType(ModelMetadata metadata, ControllerContext context) {
\r
60 return GetValidators(metadata, context, GetTypeDescriptor(metadata.ModelType).GetAttributes().Cast<Attribute>());
\r