當前位置: 首頁>>代碼示例>>C#>>正文


C# ValidationAttribute.GetType方法代碼示例

本文整理匯總了C#中System.ComponentModel.DataAnnotations.ValidationAttribute.GetType方法的典型用法代碼示例。如果您正苦於以下問題:C# ValidationAttribute.GetType方法的具體用法?C# ValidationAttribute.GetType怎麽用?C# ValidationAttribute.GetType使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.ComponentModel.DataAnnotations.ValidationAttribute的用法示例。


在下文中一共展示了ValidationAttribute.GetType方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: AdapterFactory_RegistersAdapters_ForDataTypeAttributes

        public void AdapterFactory_RegistersAdapters_ForDataTypeAttributes(ValidationAttribute attribute,
                                                                           string expectedRuleName)
        {
            // Arrange
            var adapters = new DataAnnotationsModelValidatorProvider().AttributeFactories;
            var adapterFactory = adapters.Single(kvp => kvp.Key == attribute.GetType()).Value;

            // Act
            var adapter = adapterFactory(attribute);

            // Assert
            var dataTypeAdapter = Assert.IsType<DataTypeAttributeAdapter>(adapter);
            Assert.Equal(expectedRuleName, dataTypeAdapter.RuleName);
        }
開發者ID:Nakro,項目名稱:Mvc,代碼行數:14,代碼來源:DataAnnotationsModelValidatorProviderTest.cs

示例2: GetAttributeValidation

        public static void GetAttributeValidation(ValidationAttribute attr, IDictionary<string, object> htmlAttributes)
        {
            var str = string.Empty;
              if (attr is RequiredAttribute)
              {
              StringLengthAttribute a = attr as StringLengthAttribute;
              htmlAttributes["required"] = null;

              }
              else if (attr is StringLengthAttribute)
              {
              StringLengthAttribute a = attr as StringLengthAttribute;
              htmlAttributes["maxlength"] = a.MaximumLength;
              htmlAttributes["minlength"] = a.MinimumLength;

              }
              else if (attr is RegularExpressionAttribute)
              {
              RegularExpressionAttribute a = attr as RegularExpressionAttribute;
              htmlAttributes["pattern"] = a.Pattern;

              }
              else if (attr is IdenticalAttribute)
              {
              IdenticalAttribute a = attr as IdenticalAttribute;
              htmlAttributes["data-fv-identical"] = "true";
              htmlAttributes["data-fv-identical-field"] = a.Field;
              }

              if (attr.ErrorMessage.IsNotNull()) {
              htmlAttributes[ ValidateMesAttr[attr.GetType()]]= attr.ErrorMessage;
              }
        }
開發者ID:alittletired,項目名稱:SolutionPlatform,代碼行數:33,代碼來源:ValidationHelper.cs

示例3: RegisterSharedResources

        /// <summary>
        /// Registers any resource type used by the given <see cref="ValidationAttribute"/> that must be shared and 
        /// have a named resource property available.
        /// </summary>
        /// <param name="validationAttribute">The <see cref="ValidationAttribute"/> instance to check.</param>
        /// <param name="attributeDeclaration">The <see cref="AttributeDeclaration"/> used to describe <paramref name="validationAttribute"/>.</param>
        protected static void RegisterSharedResources(ValidationAttribute validationAttribute, AttributeDeclaration attributeDeclaration)
        {
            string resourceName = validationAttribute.ErrorMessageResourceName;
            Type resourceType = validationAttribute.ErrorMessageResourceType;

            bool isEmptyResourceName = string.IsNullOrEmpty(resourceName);
            Type validateionAttributeType = validationAttribute.GetType();

            // At least one is non-null.  If the other is null, we have a problem.  We need both to
            // localize properly, or neither to signal we use the static string version
            if ((resourceType != null && isEmptyResourceName) || (resourceType == null && !isEmptyResourceName))
            {
                string resourceTypeMessage = resourceType != null ? resourceType.Name : Resource.Unspecified_Resource_Element;
                string resourceNameMessage = isEmptyResourceName ? Resource.Unspecified_Resource_Element : resourceName;

                attributeDeclaration.Errors.Add(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resource.ClientCodeGen_ValidationAttribute_Requires_ResourceType_And_Name,
                        validateionAttributeType,
                        resourceTypeMessage,
                        resourceNameMessage));
                return;
            }

            if (resourceType != null)
            {
                PropertyInfo resourceProperty = resourceType.GetProperty(resourceName);

                if (resourceProperty == null)
                {
                    attributeDeclaration.Errors.Add(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resource.ClientCodeGen_ValidationAttribute_ResourcePropertyNotFound,
                            validateionAttributeType,
                            resourceName,
                            resourceType));
                }
                else
                {
                    attributeDeclaration.RequiredTypes.Add(resourceType);
                    attributeDeclaration.RequiredProperties.Add(resourceProperty);
                }
            }
        }
開發者ID:OpenRIAServices,項目名稱:OpenRiaServices,代碼行數:52,代碼來源:ValidationCustomAttributeBuilder.cs

示例4: GetAttributeAdapter

        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer localizer)
        {
            Type type = attribute.GetType();
            if (type == typeof(RequiredAttribute))
                return new RequiredAdapter((RequiredAttribute)attribute);

            if (type == typeof(StringLengthAttribute))
                return new StringLengthAdapter((StringLengthAttribute)attribute);

            if (type == typeof(EmailAddressAttribute))
                return new EmailAddressAdapter((EmailAddressAttribute)attribute);

            if (type == typeof(GreaterThanAttribute))
                return new GreaterThanAdapter((GreaterThanAttribute)attribute);

            if (type == typeof(MinLengthAttribute))
                return new MinLengthAdapter((MinLengthAttribute)attribute);

            if (type == typeof(MaxValueAttribute))
                return new MaxValueAdapter((MaxValueAttribute)attribute);

            if (type == typeof(MinValueAttribute))
                return new MinValueAdapter((MinValueAttribute)attribute);

            if (type == typeof(FileSizeAttribute))
                return new FileSizeAdapter((FileSizeAttribute)attribute);

            if (type == typeof(EqualToAttribute))
                return new EqualToAdapter((EqualToAttribute)attribute);

            if (type == typeof(IntegerAttribute))
                return new IntegerAdapter((IntegerAttribute)attribute);

            if (type == typeof(DigitsAttribute))
                return new DigitsAdapter((DigitsAttribute)attribute);

            if (type == typeof(RangeAttribute))
                return new RangeAdapter((RangeAttribute)attribute);

            return null;
        }
開發者ID:NonFactors,項目名稱:MVC6.Template,代碼行數:41,代碼來源:ValidationAdapterProvider.cs

示例5: FileExtensionsAttributeAdapter

 public FileExtensionsAttributeAdapter(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)
     : base(metadata, context, attribute)
 {
     Contract.Assert(attribute.GetType() == ValidationAttributeHelpers.FileExtensionsAttributeType);
 }
開發者ID:Benguan,項目名稱:Code,代碼行數:5,代碼來源:FileExtensionsAttributeAdapter.cs

示例6: GetAttributeAdapter

        /// <summary>
        /// Creates an <see cref="IAttributeAdapter"/> for the given attribute.
        /// </summary>
        /// <param name="attribute">The attribute to create an adapter for.</param>
        /// <param name="stringLocalizer">The localizer to provide to the adapter.</param>
        /// <returns>An <see cref="IAttributeAdapter"/> for the given attribute.</returns>
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            IAttributeAdapter adapter;

            var type = attribute.GetType();

            if (type == typeof(RegularExpressionAttribute))
            {
                adapter = new RegularExpressionAttributeAdapter((RegularExpressionAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(MaxLengthAttribute))
            {
                adapter = new MaxLengthAttributeAdapter((MaxLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(RequiredAttribute))
            {
                adapter = new RequiredAttributeAdapter((RequiredAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(CompareAttribute))
            {
                adapter = new CompareAttributeAdapter((CompareAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(MinLengthAttribute))
            {
                adapter = new MinLengthAttributeAdapter((MinLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(CreditCardAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "creditcard", stringLocalizer);
            }
            else if (type == typeof(StringLengthAttribute))
            {
                adapter = new StringLengthAttributeAdapter((StringLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(RangeAttribute))
            {
                adapter = new RangeAttributeAdapter((RangeAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(EmailAddressAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "email", stringLocalizer);
            }
            else if (type == typeof(PhoneAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "phone", stringLocalizer);
            }
            else if (type == typeof(UrlAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "url", stringLocalizer);
            }
            else
            {
                adapter = null;
            }

            return adapter;
        }
開發者ID:phinq19,項目名稱:git_example,代碼行數:68,代碼來源:ValidationAttributeAdapterProvider.cs

示例7: AdapterFactory_RegistersAdapters_ForDataAnnotationAttributes

        public void AdapterFactory_RegistersAdapters_ForDataAnnotationAttributes(ValidationAttribute attribute,
                                                                                 Type expectedAdapterType)
        {
            // Arrange
            var adapters = new DataAnnotationsModelValidatorProvider().AttributeFactories;
            var adapterFactory = adapters.Single(kvp => kvp.Key == attribute.GetType()).Value;

            // Act
            var adapter = adapterFactory(attribute);

            // Assert
            Assert.IsType(expectedAdapterType, adapter);
        }
開發者ID:Nakro,項目名稱:Mvc,代碼行數:13,代碼來源:DataAnnotationsModelValidatorProviderTest.cs

示例8: HandleErrorMessage

        protected virtual void HandleErrorMessage(Type type, string propertyName, ValidationAttribute attribute)
        {
            string languageKey = null;

            if (attribute is DataTypeAttribute)
            {
                var metadata = attribute.TypeId.GetType();
            }
            else if (attribute is RemoteAttribute)
            {

            }
            else {
                languageKey = attribute.GetType().Name;

                if (attribute.ErrorMessageResourceName == null)
                {

                    attribute.ErrorMessage = LangResource.Resources.GetString(languageKey);

                    if (string.IsNullOrEmpty(attribute.ErrorMessage))
                        attribute.ErrorMessage = string.Format("[[{0}]]", languageKey);
                }
            }
        }
開發者ID:sbudihar,項目名稱:SIRIUSrepo,代碼行數:25,代碼來源:LocalizedDataAnnotationsModelMetadataProvider.cs

示例9: GetMissingTranslationMessage

        /// <summary>
        /// Get default message if the localized string is missing
        /// </summary>
        /// <param name="metadata">Model meta data</param>
        /// <param name="attr">Attribute to translate</param>
        /// <returns>Formatted message</returns>
        protected virtual string GetMissingTranslationMessage(ModelMetadata metadata, ValidationAttribute attr)
        {
            _logger.Warning("Failed to find translation for " + attr.GetType().Name + " on " +
                            metadata.ContainerType + "." + metadata.PropertyName);


            return string.Format("[{0}: {1}]", CultureInfo.CurrentUICulture.Name,
                                 attr.GetType().Name.Replace("Attribute", ""));
        }
開發者ID:jefth,項目名稱:griffin.mvccontrib,代碼行數:15,代碼來源:LocalizedModelValidatorProvider.cs

示例10: HandleErrorMessage

        /// <summary>
        /// Handle the error message of a validation attribute.
        /// </summary>
        protected virtual void HandleErrorMessage(Type type, string propertyName, ValidationAttribute attribute)
        {
            var languageKey = GetErrorMessageLanguageKey(type, propertyName, attribute.GetType().Name);

            if (Translator.TranslationExists(languageKey) && OverrideMode)
                attribute.ErrorMessage = Translator.Translate(languageKey);

            if (string.IsNullOrEmpty(attribute.ErrorMessage))
                attribute.ErrorMessage = string.Format("[[{0}]]", languageKey);
        }
開發者ID:niklasmelinder,項目名稱:NExtra,代碼行數:13,代碼來源:LocalizedDataAnnotationsModelMetadataProvider.cs

示例11: Validate_IsValidFalse_StringLocalizerGetsArguments

        public void Validate_IsValidFalse_StringLocalizerGetsArguments(
            ValidationAttribute attribute,
            string model,
            object[] values)
        {
            // Arrange
            var stringLocalizer = new Mock<IStringLocalizer>();

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute,
                stringLocalizer.Object);

            var metadata = _metadataProvider.GetMetadataForType(typeof(SampleModel));
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: model);

            // Act
            validator.Validate(validationContext);

            // Assert
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(values) + " " + attribute.GetType().Name;

            stringLocalizer.Verify(l => l[LocalizationKey, values], json);
        }
開發者ID:phinq19,項目名稱:git_example,代碼行數:29,代碼來源:DataAnnotationsModelValidatorTest.cs

示例12: CanHandle

 public override bool CanHandle(ValidationAttribute attribute)
 {
     return attribute.GetType() == typeof(OddLengthStringAttribute);
 }
開發者ID:Borzoo,項目名稱:Nancy,代碼行數:4,代碼來源:OddLengthStringAttributeAdapter.cs

示例13: GetMissingTranslationMessage

 /// <summary>
 /// Get default message if the localized string is missing
 /// </summary>
 /// <param name="metadata">Model meta data</param>
 /// <param name="attr">Attribute to translate</param>
 /// <returns>Formatted message</returns>
 protected virtual string GetMissingTranslationMessage(ModelMetadata metadata, ValidationAttribute attr)
 {
     return string.Format("[{0}: {1}]", CultureInfo.CurrentUICulture.Name,
                          attr.GetType().Name.Replace("Attribute", ""));
 }
開發者ID:paulzhousz,項目名稱:YOYOHRMS,代碼行數:11,代碼來源:LocalizedModelValidatorProvider.cs

示例14: CopyAttribute

        private ValidationAttribute CopyAttribute(ValidationAttribute attribute)
        {
            ValidationAttribute result = null;

            if (attribute is RangeAttribute)
            {
                var attr = (RangeAttribute)attribute;
                result = (attr.Minimum is double)
                    ?  new RangeAttribute((double)attr.Minimum, (double)attr.Maximum)
                    :  new RangeAttribute((int)attr.Minimum, (int)attr.Maximum);
            }

            if (attribute is RegularExpressionAttribute)
            {
                var attr = (RegularExpressionAttribute)attribute;
                result = new RegularExpressionAttribute(attr.Pattern);
            }

            if (attribute is RequiredAttribute)
                result = new RequiredAttribute();

            if (attribute is StringLengthAttribute)
            {
                var attr = (StringLengthAttribute)attribute;
                result = new StringLengthAttribute(attr.MaximumLength)
                {
                    MinimumLength = attr.MinimumLength
                };
            }

            if (attribute is DA.CompareAttribute)
            {
                var attr = (DA.CompareAttribute)attribute;
                result = new DA.CompareAttribute(attr.OtherProperty);
            }

            if (attribute is DataTypeAttribute)
            {
                var attr = (DataTypeAttribute)attribute;
                result = new DataTypeAttribute(attr.DataType);
            }

            if (result == null && attribute.GetType().GetInterfaces().Contains(typeof(ICloneable)))
                result = ((ICloneable)attribute).Clone() as ValidationAttribute;

            return result;
        }
開發者ID:Knoema,項目名稱:Localization,代碼行數:47,代碼來源:ValidationLocalizer.cs

示例15: AdapterFactory_RegistersAdapters_ForDataTypeAttributes

        public void AdapterFactory_RegistersAdapters_ForDataTypeAttributes(
            ValidationAttribute attribute,
            string expectedRuleName)
        {
            // Arrange
            var adapters = new DataAnnotationsClientModelValidatorProvider(
                new TestOptionsManager<MvcDataAnnotationsLocalizationOptions>(),
                stringLocalizerFactory: null)
                .AttributeFactories;
            var adapterFactory = adapters.Single(kvp => kvp.Key == attribute.GetType()).Value;

            // Act
            var adapter = adapterFactory(attribute, stringLocalizer: null);

            // Assert
            var dataTypeAdapter = Assert.IsType<DataTypeAttributeAdapter>(adapter);
            Assert.Equal(expectedRuleName, dataTypeAdapter.RuleName);
        }
開發者ID:huoxudong125,項目名稱:Mvc,代碼行數:18,代碼來源:DataAnnotationsClientModelValidatorProviderTest.cs


注:本文中的System.ComponentModel.DataAnnotations.ValidationAttribute.GetType方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。