private void ValidateAttribute(PropertyInfo property, ValidationAttribute attribute) { bool isValid = attribute.IsValid(property.GetValue(_target)); if (isValid) return; _result.Add(new ValidationResult(GetErrorMessage(attribute))); }
public void Validate(ValidationAttribute attribute, object value, ValidationContext validationContext, bool isValid) { if (isValid) { attribute.Validate(value, validationContext); Assert.Equal(ValidationResult.Success, attribute.GetValidationResult(value, validationContext)); // Run the validation twice, in case attributes cache anything attribute.Validate(value, validationContext); Assert.Equal(ValidationResult.Success, attribute.GetValidationResult(value, validationContext)); } else { Assert.Throws<ValidationException>(() => attribute.Validate(value, validationContext)); Assert.NotNull(attribute.GetValidationResult(value, validationContext)); // Run the validation twice, in case attributes cache anything Assert.Throws<ValidationException>(() => attribute.Validate(value, validationContext)); Assert.NotNull(attribute.GetValidationResult(value, validationContext)); } if (!attribute.RequiresValidationContext) { Assert.Equal(isValid, attribute.IsValid(value)); // Run the validation twice, in case attributes cache anything Assert.Equal(isValid, attribute.IsValid(value)); } }
private string GetErrorMessage(ValidationAttribute attribute) { if (!string.IsNullOrEmpty(attribute.ErrorMessage)) return attribute.ErrorMessage; return string.Format("{0},{1},{2}", attribute.ErrorMessageResourceType.FullName, attribute.ErrorMessageResourceName, attribute.ErrorMessageResourceType.Assembly); }
public IValidationRule FindRule(ValidationAttribute attr) { foreach (var attribute in attr.GetType().GetCustomAttributes(true)) { var ruleMapping = attribute as RuleMappingAttribute; if (ruleMapping != null) { return (IValidationRule)Activator.CreateInstance(ruleMapping.RuleType); } } return null; }
protected override bool DoValidate(ValidationAttribute attr, object value) { RequiredFieldAttribute attribute = attr as RequiredFieldAttribute; if (attribute == null) throw new ArgumentNullException("attr must be type of RequiredFieldAttribute"); string input = value as string; bool valid = true; if (!attribute.AllowWhiteSpace) valid = !string.IsNullOrEmpty(input) && input.Trim().Length > 0; else valid = !string.IsNullOrEmpty(input); return valid; }
protected override bool DoValidate(ValidationAttribute attr, object value) { RegularExpressionAttribute attribute = attr as RegularExpressionAttribute; if (attribute == null) throw new ArgumentNullException("attr must be type of RegularExpressionAttribute"); Regex regex = new Regex(attribute.Pattern); var input = value as string; bool valid = true; if (!string.IsNullOrEmpty(input)) { valid = regex.IsMatch(input); } return valid; }
public string Validate(ValidationAttribute attr, object value) { bool valid = DoValidate(attr, value); if (valid) return string.Empty; if (attr.ErrorMessageResourceName != null && attr.ErrorMessageResourceType != null) { ResourceManager rm = new ResourceManager(attr.ErrorMessageResourceType); return rm.GetString(attr.ErrorMessageResourceName); } return attr.DefaultErrorMessage; }
protected override bool DoValidate(ValidationAttribute attr, object value) { LengthConstraintAttribute attribute = attr as LengthConstraintAttribute; if (attribute == null) throw new ArgumentNullException("attr must be type of LengthConstraintAttribute"); string input = value as string; bool valid = true; if (string.IsNullOrEmpty(input)) return valid; valid = input.Length >= attribute.MinimumLength && input.Length <= attribute.MaximumLength; return valid; }
protected virtual string GetValidationErrorMessage(ValidationAttribute validation, MemberInfo memberInfo, object value) { if (validation.ErrorMessage.IsNotEmpty()) { return(validation.ErrorMessage); } var errorMessage = validation.FormatErrorMessage(memberInfo.Name); if (errorMessage.IsNotEmpty()) { return(errorMessage); } errorMessage = value?.ToString() ?? "null"; return(InternalResource.ValidationErrorMessageFormat.Format(memberInfo.MemberType.ToString().AsCamelCasing(), errorMessage, validation.GetType().GetDisplayNameWithNamespace())); }
private void ValidateAttributes(ParameterInfo parameter, object args, ModelStateDictionary modelState) { foreach (CustomAttributeData attributeData in parameter.CustomAttributes) { Attribute?attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType); ValidationAttribute validationAttribute = attributeInstance as ValidationAttribute; if (validationAttribute != null) { bool isValid = validationAttribute.IsValid(args); if (!isValid) { modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name)); } } } }
/// <summary> /// Get client rules /// </summary> /// <param name="metadata">Model meta data</param> /// <param name="context">Controller context</param> /// <param name="attr">Attribute being localized</param> /// <param name="formattedError">Localized error message</param> /// <returns>Collection (may be empty) with error messages for client side</returns> protected virtual IEnumerable <ModelClientValidationRule> GetClientRules(ModelMetadata metadata, ControllerContext context, ValidationAttribute attr, string formattedError) { var clientValidable = attr as IClientValidatable; var clientRules = clientValidable == null ? _adapterFactory.Create(attr, formattedError) : clientValidable.GetClientValidationRules( metadata, context).ToList(); foreach (var clientRule in clientRules) { clientRule.ErrorMessage = formattedError; } return(clientRules); }
/// <summary> /// Retrieves the member attributes. /// </summary> protected override void RetrieveMemberAttributes() { List <PropertyInfo> propertyInfos = new List <PropertyInfo>(MemberType.GetProperties(BindingFlags.Public | BindingFlags.Instance)); foreach (PropertyInfo info in propertyInfos) { List <Attribute> propertyAttributes = new List <Attribute>(Attribute.GetCustomAttributes(info, typeof(ValidationAttribute), true)); foreach (Attribute attribute in propertyAttributes) { if (attribute is ValidationAttribute) { ValidationAttribute att = (ValidationAttribute)attribute; att.Target = info.GetValue(BuilderSource.Action, null); ValidationAttributes.Add(att); } } } }
/// <summary> /// Sets the default error message on a <see cref="ValidationAttribute"/> by replacing it with /// modified ErrorMessageString. /// </summary> /// <param name="validationAttribute">Validation attributes to modify.</param> public static void SetDefaultErrorMessage(ValidationAttribute validationAttribute) { if (validationAttribute is StringLengthAttribute stringLengthAttribute && stringLengthAttribute.MinimumLength != 0) { var customErrorMessageSet = ValidationAttributeCustomErrorMessageSetProperty.GetValue(validationAttribute) as bool?; if (customErrorMessageSet != true) { // This message is used by StringLengthAttribute internally so we need to copy the save behavior here. validationAttribute.ErrorMessage = SetErrorMessagePlaceholders("The field {0} must be a string with a minimum length of {2} and a maximum length of {1}."); return; } } // We need to replace placeholders with temporary characters so that Blazor validation will not override // our messages. validationAttribute.ErrorMessage = SetErrorMessagePlaceholders(ValidationAttributeErrorMessageStringProperty.GetValue(validationAttribute) as string); }
/// <summary> /// 验证Class /// </summary> /// <param name="contextParameter"></param> /// <param name="parameterType"></param> private void ValidClass(object contextParameter, Type parameterType) { PropertyInfo[] propertyInfos = parameterType.GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfos) { object value = propertyInfo.GetValue(contextParameter); List <ValidationAttribute> customAttributes = propertyInfo.GetCustomAttributes <ValidationAttribute>().ToList(); if (customAttributes.Count <= 0) { continue; } ValidationAttribute requiredAttribute = customAttributes.FirstOrDefault(m => m is RequiredAttribute); if (requiredAttribute != null || !value.IsNullOrEmptyString()) { Valid(customAttributes, value); } } }
/// <summary> /// Returns the <see cref="IAttributeAdapter"/> for a given <see cref="ValidationAttribute"/> attribute. /// </summary> /// <param name="attribute">The <see cref="ValidationAttribute"/> for which <see cref="IAttributeAdapter"/> will be provided.</param> /// <param name="stringLocalizer">The <see cref="IStringLocalizer"/> which will be used to create messages.</param> /// <returns>An <see cref="IAttributeAdapter"/> for the given attribute.</returns> public virtual IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer) { switch (attribute) { case CompareToAttribute compareToAttribute: return(new CompareToAttributeAdapter(compareToAttribute, stringLocalizer)); case FileAttribute fileAttribute: return(new FileAttributeAdapter(fileAttribute, stringLocalizer)); case FileMaxSizeAttribute fileMaxSizeAttribute: return(new FileMaxSizeAttributeAdapter(fileMaxSizeAttribute, stringLocalizer)); case FileMinSizeAttribute fileMinSizeAttribute: return(new FileMinSizeAttributeAdapter(fileMinSizeAttribute, stringLocalizer)); case FileTypeAttribute fileTypeAttribute: return(new FileTypeAttributeAdapter(fileTypeAttribute, stringLocalizer)); case FixedLengthAttribute fixedLengthAttribute: return(new FixedLengthAttributeAdapter(fixedLengthAttribute, stringLocalizer)); case MaxAgeAttribute maxAgeAttribute: return(new MaxAgeAttributeAdapter(maxAgeAttribute, stringLocalizer)); case MaxDateAttribute maxDateAttribute: return(new MaxDateAttributeAdapter(maxDateAttribute, stringLocalizer)); case MinAgeAttribute minAgeAttribute: return(new MinAgeAttributeAdapter(minAgeAttribute, stringLocalizer)); case MinDateAttribute minDateAttribute: return(new MinDateAttributeAdapter(minDateAttribute, stringLocalizer)); case RequiredIfAttribute requiredIfAttribute: return(new RequiredIfAttributeAdapter(requiredIfAttribute, stringLocalizer)); case TextEditorRequiredAttribute textEditorRequiredAttribute: return(new TextEditorRequiredAttributeAdapter(textEditorRequiredAttribute, stringLocalizer)); default: return(_baseProvider.GetAttributeAdapter(attribute, stringLocalizer)); } }
/// <summary> /// 解析 <see cref="ValidationAttribute"/> 对象。 /// </summary> /// <param name="settings"></param> /// <param name="validation">要解析的 <see cref="ValidationAttribute"/> 对象。</param> /// <param name="validTypes">如果 <paramref name="validation"/> 能与 EasyUI 的客户端验证所对应,则添加到 validType 属性中。</param> protected virtual void ParseValidation(ValidateBoxSettings settings, ValidationAttribute validation, List <string> validTypes) { //必填验证特性 if (validation is RequiredAttribute required) { settings.Required = true; return; } //长度验证特性 if (validation is StringLengthAttribute stringLength) { validTypes.Add(string.Format("length[{0},{1}]", stringLength.MinimumLength, stringLength.MaximumLength)); return; } //电话验证特性 if (validation is TelphoneAttribute telphone) { validTypes.Add("phone"); return; } //手机验证特性 if (validation is MobileAttribute mobile) { validTypes.Add("mobile"); return; } //手机或电话验证特性 if (validation is TelphoneOrMobileAttribute telOrMobile) { validTypes.Add("phoneOrMobile"); return; } //邮箱验证特性 if (validation is EmailAttribute email) { validTypes.Add("email"); return; } }
/// <summary> /// Create a new instance of <see cref="DataAnnotationsModelValidator"/>. /// </summary> /// <param name="attribute">The <see cref="ValidationAttribute"/> that defines what we're validating.</param> /// <param name="stringLocalizer">The <see cref="IStringLocalizer"/> used to create messages.</param> /// <param name="validationAttributeAdapterProvider">The <see cref="IValidationAttributeAdapterProvider"/> /// which <see cref="ValidationAttributeAdapter{TAttribute}"/>'s will be created from.</param> public DataAnnotationsModelValidator( IValidationAttributeAdapterProvider validationAttributeAdapterProvider, ValidationAttribute attribute, IStringLocalizer stringLocalizer) { if (validationAttributeAdapterProvider == null) { throw new ArgumentNullException(nameof(validationAttributeAdapterProvider)); } if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } _validationAttributeAdapterProvider = validationAttributeAdapterProvider; Attribute = attribute; _stringLocalizer = stringLocalizer; }
/// <summary> /// Copy from .NET 4.0 source code /// </summary> public static ValidationResult GetValidationResult(this ValidationAttribute att, object value, ValidationContext context) { var memberName = context.MemberName; try { att.Validate(value, memberName); } catch (Exception ex) { //NOTE: The MemberName could be set after the IsValid method is executed if (att is IHasMemberName) { memberName = (att as IHasMemberName).MemberName ?? context.MemberName; } return(new ValidationResult(ex.Message, string.IsNullOrEmpty(memberName) ? null : new[] { memberName })); } return(null); }
public static ValidationResult IsValid(this ValidationAttribute validationAttribute, object value, ValidationContext validationContext) { //if (validationAttribute._hasBaseIsValid) //{ // // this means neither of the IsValid methods has been overriden, throw. // throw new NotImplementedException(DataAnnotationsResources.ValidationAttribute_IsValid_NotImplemented); //} ValidationResult result = ValidationResult.Success; // call overridden method. if (!validationAttribute.IsValid(value)) { string[] memberNames = validationContext.MemberName != null ? new string[] { validationContext.MemberName } : null; result = new ValidationResult(validationAttribute.FormatErrorMessage(validationContext.DisplayName), memberNames); } return(result); }
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); }
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(MinLengthAttribute)) { adapter = new MinLengthAttributeAdapter((MinLengthAttribute)attribute, stringLocalizer); } else if (type == typeof(StringLengthAttribute)) { adapter = new StringLengthAttributeAdapter((StringLengthAttribute)attribute, stringLocalizer); } else if (type == typeof(RangeAttribute)) { adapter = new RangeAttributeAdapter((RangeAttribute)attribute, stringLocalizer); } else { adapter = null; } return(adapter); }
/// <summary> /// /// </summary> /// <param name="metadata">Model meta data</param> /// <param name="attr">Attribute to localize</param> /// <param name="errorMessage">Localized message with <c>{}</c> formatters.</param> /// <returns>Formatted message (<c>{}</c> has been replaced with values)</returns> protected virtual string FormatErrorMessage( ModelMetadata metadata, ValidationAttribute attr, string errorMessage) { string formattedError; try { lock (attr) { attr.ErrorMessage = errorMessage; formattedError = attr.FormatErrorMessage(metadata.GetDisplayName()); attr.ErrorMessage = WorkaroundMarker; } } catch (Exception err) { formattedError = err.Message; } return(formattedError); }
static public void TrySetErrorMessage(this ValidationAttribute attr, string dictionaryKey) { if (string.IsNullOrEmpty(dictionaryKey)) { return; } var item = UmbracoValidationHelper.GetDictionaryItem(dictionaryKey); if (item != dictionaryKey) { // dictionaryKey has entry in dictionary, use entry value as error message attr.ErrorMessage = item; } else { // dictionaryKey does not have entry in dictionary, assume it is error message attr.ErrorMessage = dictionaryKey; } }
public override void SetValue(object component, object value) { List <Attribute> attributes = new List <Attribute>(); this.FillAttributes(attributes); foreach (Attribute attribute in attributes) { ValidationAttribute validationAttribute = attribute as ValidationAttribute; if (null == validationAttribute) { continue; } //if (!validationAttribute.IsValid(value)) // throw new ValidationException(validationAttribute.ErrorMessage, validationAttribute, component); } this._orginal.SetValue(component, value); }
private static bool IsValid(ValidationAttribute validationAttribute, FormValidationContext validationContext, out ValidationResult result) { if (validationAttribute.IsValid(validationContext.Value) == false) { if (validationContext.Rule.Message != null) { validationAttribute.ErrorMessage = validationContext.Rule.Message; } string errorMessage = validationAttribute.FormatErrorMessage(validationContext.DisplayName); result = new ValidationResult(errorMessage, new string[] { validationContext.FieldName }); return(false); } result = null; return(true); }
/// <summary> /// Populates the error message from the given metadata. /// </summary> /// <param name="validationAttribute"></param> public void PopulateErrorMessage([NotNull] ValidationAttribute validationAttribute) { //Invariant.IsNotNull(validationAttribute, "validationMetadata"); string errorMessage = null; if (ErrorMessage != null) { errorMessage = ErrorMessage(); } if (!string.IsNullOrEmpty(errorMessage)) { validationAttribute.ErrorMessage = errorMessage; } else if (ErrorMessageResourceType != null && !string.IsNullOrEmpty(ErrorMessageResourceName)) { validationAttribute.ErrorMessageResourceType = ErrorMessageResourceType; validationAttribute.ErrorMessageResourceName = ErrorMessageResourceName; } else if (LocalizationConventions.Enabled) { // enables support for partial matadata if (ErrorMessageResourceType != null) { validationAttribute.ErrorMessageResourceType = ErrorMessageResourceType; } if (!string.IsNullOrEmpty(ErrorMessageResourceName)) { validationAttribute.ErrorMessageResourceName = ErrorMessageResourceName; } var conventionType = modelMetadata.With(m => m.ContainerType); var propertyName = modelMetadata.With(m => m.PropertyName); var defaultResourceType = LocalizationConventions.GetDefaultResourceType(conventionType); var transformer = ConventionalDataAnnotationsModelMetadataProvider.ValidationAttributeTransformer.Value; transformer.Transform(validationAttribute, conventionType, propertyName, defaultResourceType); } }
public static ValidationAttributeAdapter Create(ValidationAttribute attribute, string displayName) { Debug.Assert(attribute != null, "attribute parameter must not be null"); Debug.Assert(!string.IsNullOrWhiteSpace(displayName), "displayName parameter must not be null, empty or whitespace string"); // Added suport for ValidationAttribute subclassing. See http://davalidation.codeplex.com/workitem/695 var baseType = attribute.GetType(); Func <ValidationAttribute, string, ValidationAttributeAdapter> predefinedCreator; do { if (!PredefinedCreators.TryGetValue(baseType, out predefinedCreator)) { baseType = baseType.BaseType; } }while (predefinedCreator == null && baseType != null && baseType != typeof(Attribute)); return(predefinedCreator != null ? predefinedCreator(attribute, displayName) : new ValidationAttributeAdapter(attribute, displayName)); }
public virtual IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer) { var type = attribute.GetType(); if (type == typeof(DynamicStringLengthAttribute)) { return(new DynamicStringLengthAttributeAdapter((DynamicStringLengthAttribute)attribute, stringLocalizer)); } if (type == typeof(DynamicMaxLengthAttribute)) { return(new DynamicMaxLengthAttributeAdapter((DynamicMaxLengthAttribute)attribute, stringLocalizer)); } if (type == typeof(DynamicRangeAttribute)) { return(new DynamicRangeAttributeAdapter((DynamicRangeAttribute)attribute, stringLocalizer)); } return(_defaultAdapter.GetAttributeAdapter(attribute, stringLocalizer)); }
public override ValidationResult GetOrDefault(ValidationAttribute validationAttribute, object validatingObject, ValidationContext validationContext) { var resourceSource = _abpMvcDataAnnotationsLocalizationOptions.AssemblyResources.GetOrDefault(validationContext.ObjectType.Assembly); if (resourceSource == null) { return(base.GetOrDefault(validationAttribute, validatingObject, validationContext)); } if (validationAttribute.ErrorMessage == null) { ValidationAttributeHelper.SetDefaultErrorMessage(validationAttribute); } if (validationAttribute.ErrorMessage != null) { validationAttribute.ErrorMessage = _stringLocalizerFactory.Create(resourceSource)[validationAttribute.ErrorMessage]; } return(base.GetOrDefault(validationAttribute, validatingObject, validationContext)); }
public void AdapterForKnownTypeRegistered(Type attributeType, ValidationAttribute validationAttr, Type expectedAdapterType, string expectedRuleName) { // Arrange var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(object)); var context = new ControllerContext(); var adapters = DataAnnotationsModelValidatorProvider.AttributeFactories; var adapterFactory = adapters.Single(kvp => kvp.Key == attributeType).Value; // Act var adapter = adapterFactory(metadata, context, validationAttr); // Assert Assert.IsType(expectedAdapterType, adapter); if (expectedRuleName != null) { DataTypeAttributeAdapter dataTypeAdapter = adapter as DataTypeAttributeAdapter; Assert.NotNull(dataTypeAdapter); Assert.Equal(expectedRuleName, dataTypeAdapter.RuleName); } }
public void RegisterScriptsNoAttributes() { _validator.ControlToValidate = "txtClientName"; const string propertyName = "ClientName"; _validator.PropertyName = propertyName; Type bookingType = typeof(Booking); _validator.ModelType = bookingType.AssemblyQualifiedName; ValidationAttribute[] attributes = new ValidationAttribute[0]; _mockValidationRunner.Setup( runner => runner.GetValidators(bookingType, propertyName)).Returns( attributes).Verifiable(); _validator.RegisterScripts(); _mockRuleProvider.Verify(provider => provider.GetRules(attributes), Times.Never()); _mockValidationRunner.Verify(); _mockScriptManager.Verify(manager => manager.RegisterScripts(null), Times.Never()); }
public IAttributeAdapter?GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer?stringLocalizer) { return(attribute switch { StringLengthAttribute stringLength => new StringLengthAdapter(stringLength), GreaterThanAttribute greaterThan => new GreaterThanAdapter(greaterThan), AcceptFilesAttribute acceptFiles => new AcceptFilesAdapter(acceptFiles), MinLengthAttribute minLength => new MinLengthAdapter(minLength), EmailAddressAttribute email => new EmailAddressAdapter(email), RequiredAttribute required => new RequiredAdapter(required), MaxValueAttribute maxValue => new MaxValueAdapter(maxValue), MinValueAttribute minValue => new MinValueAdapter(minValue), LessThanAttribute lessThan => new LessThanAdapter(lessThan), FileSizeAttribute fileSize => new FileSizeAdapter(fileSize), EqualToAttribute equalTo => new EqualToAdapter(equalTo), IntegerAttribute integer => new IntegerAdapter(integer), DigitsAttribute digits => new DigitsAdapter(digits), NumberAttribute number => new NumberAdapter(number), RangeAttribute range => new RangeAdapter(range), _ => null });
/// <summary> /// Retrieves either the error message directly or the text coming from the resources. /// </summary> /// <param name="attribute">The validation attribute which defines the message or resource name.</param> /// <returns>Either the message, the resolved message or <c>null</c> if the resource was not found.</returns> /// <exception cref="InvalidOperationException"> /// Is thrown if the resource mananger could not be instantiated using the /// provided resource type. /// </exception> public static string ResolveErrorMessage(this ValidationAttribute attribute) { if (!string.IsNullOrEmpty(attribute.ErrorMessage)) { // this is clear -> just return the message return(attribute.ErrorMessage); } if (string.IsNullOrEmpty(attribute.ErrorMessageResourceName) || attribute.ErrorMessageResourceType == null) { // we can't do anything because there is no ressource name given return(null); } var manager = new ResourceManager(attribute.ErrorMessageResourceType); if (manager == null) { throw new InvalidOperationException("Resource type could not be used."); } // try to return the resource based text return(manager.GetString(attribute.ErrorMessageResourceName)); }
private static void AddValidationRule(Binding binding, ValidationAttribute validationAttribute) { // TODO: support input value validation. switch (validationAttribute) { case RequiredAttribute required: binding.ValidationRules.Add(new RequiredValidationRule(required)); break; case RangeAttribute rangeAttribute: binding.ValidationRules.Add(new RangeValidationRule(rangeAttribute)); break; // TODO StringLengthAttribute // TODO RegularExpressionAttribute // TODO CustomValidationAttribute default: binding.ValidationRules.Add(new ValidationAttributeRuleBase(validationAttribute)); break; } }
/// <summary> /// Validates the given instance. /// </summary> /// <param name="instance">The instance that should be validated.</param> /// <param name="attribute">The <see cref="ValidationAttribute"/> that should be handled.</param> /// <param name="descriptor">A <see cref="PropertyDescriptor"/> instance for the property that is being validated.</param> /// <param name="context">The <see cref="NancyContext"/> of the current request.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns> public virtual IEnumerable <ModelValidationError> Validate(object instance, ValidationAttribute attribute, PropertyDescriptor descriptor, NancyContext context) { var validationContext = new ValidationContext(instance, null, null) { MemberName = descriptor == null ? null : descriptor.Name }; if (descriptor != null) { instance = descriptor.GetValue(instance); } var result = attribute.GetValidationResult(instance, validationContext); if (result != null) { yield return(new ModelValidationError(result.MemberNames, string.Join(" ", result.MemberNames.Select(attribute.FormatErrorMessage)))); } }
/// <summary> /// Gets the error from invalid attribute. /// </summary> /// <param name="attribute">The attribute.</param> /// <param name="fieldName">Name of the field.</param> /// <returns></returns> protected virtual DomainSpecificationError GetErrorFromInvalidAttribute(ValidationAttribute attribute, string fieldName) { string errorMessage = string.IsNullOrEmpty(attribute.ErrorMessage) ? null : attribute.ErrorMessage; DomainSpecificationError currentError = null; if (m_errorReasons.TryGetValue(attribute.GetType(), out currentError)) { currentError = new DomainSpecificationError(currentError.ErrorCode ?? -1, errorMessage ?? currentError.NotSatisfiedReason, fieldName); try { if (attribute is MinLengthAttribute) { var minLengthAttr = attribute as MinLengthAttribute; currentError.NotSatisfiedReason = string.Format( currentError.NotSatisfiedReason, minLengthAttr.Length); } else if (attribute is MaxLengthAttribute) { var maxLengthAttr = attribute as MaxLengthAttribute; currentError.NotSatisfiedReason = string.Format( currentError.NotSatisfiedReason, maxLengthAttr.Length); } } catch (FormatException) { } } else { currentError = new DomainSpecificationError(-1, errorMessage, fieldName); } return(currentError); }
public void DataAnnotationsErrorMessageResourceNameTest() { /// Verifies that all properties that are decorated with validation data-annotations, refer to /// an existing resource. This will make sure, that missing resources are not referenced. Assembly assembly = Assembly.Load(new AssemblyName("WebApplication_MVC")); // be sure to add dependancy to project var types = assembly.GetTypes().Where(t => t.IsClass && !t.IsAbstract); foreach (var type in types) { var properties = type.GetProperties(); foreach (PropertyInfo property in properties) { var attributes = property.GetCustomAttributes(true); foreach (var item in attributes) { if (item is ValidationAttribute) { ValidationAttribute val = item as ValidationAttribute; Assert.IsNotNull(val); if (val.ErrorMessageResourceType != null) { Assert.AreNotEqual(String.Empty, val.ErrorMessageResourceName, String.Format(@"Validation Error Resource specified on property: {0}.{1} is empty!", type.ToString(), property.Name)); try { ResourceManager rm = new ResourceManager(val.ErrorMessageResourceType); string resourceValue = rm.GetString(val.ErrorMessageResourceName); Assert.IsFalse(String.IsNullOrEmpty(resourceValue), String.Format(@"The value of the Validation Error Resource specified on property: {0}.{1} is empty!", type.ToString(), property.Name)); } catch (MissingManifestResourceException) { Assert.Fail(String.Format(@"Validation Error Resource specified on property: {0}.{1} could not be found!", type.ToString(), property.Name)); } } } } } } }
public static ValidationResult GetValidationResult(this ValidationAttribute validationAttribute, object value, ValidationContext validationContext) { if (validationContext == null) { throw new ArgumentNullException("validationContext"); } ValidationResult result = validationAttribute.IsValid(value, validationContext); // If validation fails, we want to ensure we have a ValidationResult that guarantees it has an ErrorMessage if (result != null) { bool hasErrorMessage = (result != null) ? !string.IsNullOrEmpty(result.ErrorMessage) : false; if (!hasErrorMessage) { string errorMessage = validationAttribute.FormatErrorMessage(validationContext.DisplayName); result = new ValidationResult(errorMessage, result.MemberNames); } } return(result); }
public ValidationException(string errorMessage, ValidationAttribute validatingAttribute, object value);
public ValidationException(ValidationResult validationResult, ValidationAttribute validatingAttribute, object value);
/// <summary> /// Constructor that accepts a structured <see cref="ValidationResult" /> describing the problem. /// </summary> /// <param name="validationResult">The value describing the validation error</param> /// <param name="validatingAttribute">The attribute that triggered this exception</param> /// <param name="value">The value that caused the validating attribute to trigger the exception</param> public ValidationException(ValidationResult validationResult, ValidationAttribute validatingAttribute, object value) : this(validationResult.ErrorMessage, validatingAttribute, value) { _validationResult = validationResult; }
/// <summary> /// Constructor that accepts an error message, the failing attribute, and the invalid value. /// </summary> /// <param name="errorMessage">The localized error message</param> /// <param name="validatingAttribute">The attribute that triggered this exception</param> /// <param name="value">The value that caused the validating attribute to trigger the exception</param> public ValidationException(string errorMessage, ValidationAttribute validatingAttribute, object value) : base(errorMessage) { Value = value; ValidationAttribute = validatingAttribute; }
public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_null() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; Assert.False(Validator.TryValidateValue(null, validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue(null, validationContext, validationResults, attributesToValidate)); Assert.Equal(1, validationResults.Count); // cannot check error message - not defined on ret builds }
public static IValidationRule GetRule(ValidationAttribute attr) { if (RuleLocator == null) throw new NotSupportedException("Rule locator is needed. Set RuleLocator first."); return RuleLocator.FindRule(attr); }
public static void TryValidateValue_returns_true_if_Property_has_no_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(0, validationResults.Count); }
protected virtual bool DoValidate(ValidationAttribute attr, object value) { return true; }
public static void TestValidateValueThrowsIfNoRequiredAttribute() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate)); Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); }
public TestCase(ValidationAttribute attribute, object value, ValidationContext validationContext = null) { Attribute = attribute; Value = value; ValidationContext = validationContext ?? new ValidationContext(new object()); }
public InvalidRequestEventArgs(string message, ValidationAttribute cause) { this.Message = message; this.Cause = cause; }
public static void TestValidateValueThrowsIfNullRequiredAttribute() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateValue(null, validationContext, attributesToValidate)); Assert.IsType<RequiredAttribute>(exception.ValidationAttribute); // cannot check error message - not defined on ret builds Assert.Null(exception.Value); }
internal InvalidRequestException(string message, ValidationAttribute cause) : this(message) { this.CausedAttribute = cause; }
public static void ValidateValue_succeeds_if_Property_has_no_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; Validator.ValidateValue("Valid Value", validationContext, attributesToValidate); }
public static void TryValidateValue_returns_false_if_Property_has_no_RequiredAttribute_and_value_is_invalid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); }