コード例 #1
0
 protected void HookupValidationAttributes()
 {
     PropertyInfo[] propertyInfos = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
     foreach (PropertyInfo propertyInfo in propertyInfos)
     {
         Attribute[] custom = Attribute.GetCustomAttributes(propertyInfo, typeof(ValidationAttribute), true);
         foreach (Attribute attribute in custom)
         {
             PropertyInfo        property            = propertyInfo;
             ValidationAttribute validationAttribute = attribute as ValidationAttribute;
             if (validationAttribute == null)
             {
                 throw new NotSupportedException("validationAttribute variable should be inherited from ValidationAttribute type");
             }
             string           name             = property.Name;
             DisplayAttribute displayAttribute = Attribute.GetCustomAttributes(propertyInfo, typeof(DisplayAttribute)).FirstOrDefault() as DisplayAttribute;
             if (displayAttribute != null)
             {
                 name = displayAttribute.GetName();
             }
             string message = validationAttribute.FormatErrorMessage(name);
             AddValidationFor(propertyInfo.Name).When(x => {
                 object value            = property.GetGetMethod().Invoke(this, new object[] {});
                 ValidationResult result = validationAttribute.GetValidationResult(value, new ValidationContext(this, null, null)
                 {
                     MemberName = property.Name
                 });
                 return(result != ValidationResult.Success);
             }).Show(message);
         }
     }
 }
コード例 #2
0
            public override IEnumerable <ModelValidationResult> Validate(object container)
            {
                var context = new ValidationContext(container, null, null);
                var result  = _attribute.GetValidationResult(Metadata.Model, context);

                if (result == null)
                {
                    yield break;
                }

                //if (_attribute.IsValid(Metadata.Model))
                //  yield break;

                string errorMsg;

                lock (_attribute)
                {
                    _attribute.ErrorMessage = _errorMsg;
                    errorMsg = _attribute.FormatErrorMessage(Metadata.GetDisplayName());
                    _attribute.ErrorMessage = WorkaroundMarker;
                }
                yield return(new ModelValidationResult {
                    Message = errorMsg
                });
            }
コード例 #3
0
        /// <summary>
        /// Validates the validator.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="validationIssues">The validation issues.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="property">The property.</param>
        /// <param name="validator">The validator.</param>
        protected void ValidateValidator(IList <ValidationError> validationIssues, object entity, PropertyInfo property, ValidationAttribute validator)
        {
            var value     = property.GetValue(entity, null);
            var ctxt      = new ValidationContext(entity);
            var valResult = new List <ValidationResult>();
            var result    = Validator.TryValidateValue(value, ctxt, valResult, new[] { validator });

            if (!result)
            {
                var desc         = property.GetCustomAttributes <System.ComponentModel.DescriptionAttribute>(true).FirstOrDefault();
                var errorMessage = desc == null?validator.FormatErrorMessage(property.Name)
                                       :  validator.FormatErrorMessage(desc.Description);

                validationIssues.Add(new ValidationError(errorMessage, property, value));
            }
        }
コード例 #4
0
        /// <summary>
        /// 要驗證的結構描述。
        /// </summary>
        /// <param name="relation">相關要驗證的元件。</param>
        /// <param name="source">主要驗證的元件。</param>
        /// <returns>驗證的訊息內容。</returns>
        public static IEnumerable <string> Validate(object relation, object source)
        {
            foreach (PropertyInfo propInfo in source.GetType().GetProperties())
            {
                object[] customAttributes = propInfo.GetCustomAttributes(typeof(ValidationAttribute), inherit: true);

                foreach (object customAttribute in customAttributes)
                {
                    ValidationAttribute validationAttribute = (ValidationAttribute)customAttribute;

                    bool isValid = false;
                    // 預設驗證的 Attributes。
                    if (validationAttribute.GetType() == typeof(RequiredAttribute) || validationAttribute.GetType() == typeof(RangeAttribute) ||
                        validationAttribute.GetType() == typeof(RegularExpressionAttribute) || validationAttribute.GetType() == typeof(StringLengthAttribute))
                    {
                        isValid = validationAttribute.IsValid(propInfo.GetValue(source, BindingFlags.GetProperty, null, null, null));
                    }
                    // 自訂驗證的 Attributes。
                    else
                    {
                        isValid = validationAttribute.IsValid(new object[] { propInfo.Name, propInfo.GetValue(source, BindingFlags.GetProperty, null, null, null), source, relation });
                    }

                    if (!isValid)
                    {
                        yield return(validationAttribute.FormatErrorMessage(propInfo.Name));
                    }
                }
            }
        }
コード例 #5
0
        public static ValidationResult GetValidationResult(this ValidationAttribute validationAttribute, object value, ValidationContext validationContext)
        {
            bool flag;

            if (validationContext != null)
            {
                ValidationResult validationResult = validationAttribute.IsValid(value, validationContext);
                if (validationResult != null)
                {
                    if (validationResult != null)
                    {
                        flag = !string.IsNullOrEmpty(validationResult.ErrorMessage);
                    }
                    else
                    {
                        flag = false;
                    }
                    bool flag1 = flag;
                    if (!flag1)
                    {
                        string str = validationAttribute.FormatErrorMessage(validationContext.DisplayName);
                        validationResult = new ValidationResult(str, validationResult.MemberNames);
                    }
                }
                return(validationResult);
            }
            else
            {
                throw new ArgumentNullException("validationContext");
            }
        }
コード例 #6
0
        public static ValidationResult IsValid(this ValidationAttribute validationAttribute, object value, ValidationContext validationContext)
        {
            ValidationResult validationResult;
            object           obj;

            lock (SyncLock)
            {
                ValidationResult success = ValidationResult.Success;
                if (!validationAttribute.IsValid(value))
                {
                    if (validationContext.MemberName != null)
                    {
                        string[] memberName = new string[1];
                        memberName[0] = validationContext.MemberName;
                        obj           = memberName;
                    }
                    else
                    {
                        obj = null;
                    }
                    string[] strArrays = (string[])obj;
                    success = new ValidationResult(validationAttribute.FormatErrorMessage(validationContext.DisplayName), strArrays);
                }
                validationResult = success;
            }
            return(validationResult);
        }
コード例 #7
0
        /// <summary>
        /// Adds a value to the AdditionalValues collection with a formatted validation message taken from a
        /// ValidationAttribute. Intended to be used as a shortcut for adding validation messages associated with
        /// ValidationAttributes in an implementation of IMetadataAttribute
        /// </summary>
        /// <param name="key">The name of the property (key) to add to the collection.</param>
        /// <param name="value">The value to add to the collection.</param>
        /// <param name="attribute">The attribute from which the validation message will be extracted.</param>
        /// <returns>ModelMetadata instance for method chaining</returns>
        public static DisplayMetadata AddAdditionalValueWithValidationMessage(this DisplayMetadata modelMetaData, string key, object value, ValidationAttribute attribute)
        {
            modelMetaData.AdditionalValues.Add(key, value);
            modelMetaData.AdditionalValues.Add(key + "ValMsg", attribute.FormatErrorMessage(modelMetaData.DisplayName()));

            return(modelMetaData);
        }
コード例 #8
0
        /// <summary>
        ///     Formats the localized error message to present to the user.
        /// </summary>
        /// <param name="name">The user-visible name to include in the formatted message.</param>
        /// <param name="errorMessage">localized error message</param>
        /// <returns>The localized string describing the validation error</returns>
        public string FormatErrorMessage(string name, string errorMessage = null)
        {
            if (!string.IsNullOrEmpty(errorMessage))
            {
                _validationAttribute.ErrorMessage = errorMessage;
            }

            return(_validationAttribute.FormatErrorMessage(name));
        }
コード例 #9
0
ファイル: ValidationHelper.cs プロジェクト: hanxiaomeme/CERP
        /// <summary>
        /// 获取错误消息
        /// </summary>
        private static string GetErrorMessage(string propertyName, ValidationAttribute attribute)
        {
            string message = string.Empty;

            if (!string.IsNullOrEmpty(attribute.ErrorMessage))
            {
                message = attribute.ErrorMessage;
            }
            else
            {
                message = attribute.FormatErrorMessage(propertyName);
            }
            return(message);
        }
コード例 #10
0
ファイル: Validator.cs プロジェクト: moayyaed/apptext
        private ValidationError GenerateValidationError(string prefix, string propertyName, ValidationAttribute attribute)
        {
            // Post-process validation error by converting everything after the | suffix to params (e.g. StringTooLong|0,20)
            var errorMessage       = attribute.FormatErrorMessage(propertyName);
            var errorMessageParts  = errorMessage.Split('|');
            var errorMessageText   = errorMessageParts[0];
            var errorMessageParams = errorMessageParts.Length > 1
                ? errorMessageParts[1].Split(',')
                : new object[0];

            return(new ValidationError {
                Name = $"{prefix}{propertyName}", ErrorMessage = errorMessageText, Parameters = errorMessageParams
            });
        }
コード例 #11
0
 public static string GetValidationError(this PropertyDescriptor propertyDescriptor, object value)
 {
     foreach (object attrib in propertyDescriptor.Attributes)
     {
         ValidationAttribute validationAttribute = attrib as ValidationAttribute;
         if (validationAttribute != null)
         {
             if (!validationAttribute.IsValid(value))
             {
                 return(validationAttribute.FormatErrorMessage(propertyDescriptor.Name));
             }
         }
     }
     return("");
 }
コード例 #12
0
        private ValidationResult Validate(ValidationAttribute validator, string propertyName, object propertyValue, string parentPropertyName)
        {
            var isValid = validator.IsValid(propertyValue);

            if (isValid)
            {
                return(ValidationResult.Success);
            }

            // Prepare error message.
            var errorMessage = validator.FormatErrorMessage(propertyName);

            // Prepare member names, considering parent property.
            var memberNames = BuildMemberNames(propertyName, parentPropertyName);

            return(new ValidationResult(errorMessage, memberNames));
        }
コード例 #13
0
        private void AddAttributeValidator(PropertyInfo propertyInfo, ValidationAttribute validationAttribute)
        {
            string name = propertyInfo.Name;

            DisplayAttribute displayAttribute = propertyInfo.GetCustomAttributes <DisplayAttribute>().FirstOrDefault();

            if (displayAttribute != null)
            {
                name = displayAttribute.GetName();
            }

            // Note: See localization guidelines to properly localize the message
            ValidationResult validationResult = null;

            AddValidationFor <TBindingModel>(propertyInfo.Name, validationAttribute)
            .When(
                x =>
            {
                object value = propertyInfo.GetMethod.Invoke(this, new object[] { });
                ValidationContext validationContext =
                    new ValidationContext(this)
                {
                    MemberName = propertyInfo.Name
                };

                validationResult = validationAttribute.GetValidationResult(value, validationContext);
                return(validationResult != ValidationResult.Success);
            })
            .ShowMessage(
                (validatingModel) =>
            {
                string result;

                if (validationResult != null && !String.IsNullOrEmpty(validationResult.ErrorMessage))
                {
                    result = validationResult.ErrorMessage;
                }
                else
                {
                    result = validationAttribute.FormatErrorMessage(name);
                }

                return(result);
            });
        }
コード例 #14
0
        /// <summary>
        /// Applies the validation attributes.
        /// </summary>
        /// <param name="attr">The attribute.</param>
        /// <param name="pi">The property info.</param>
        private static void ApplyValidationAttributes(this AttributeModel attr, PropertyInfo pi)
        {
            attr.Validations = new Dictionary <string, ValidationAttribute>();
            Type modelType = typeof(AttributeModel);
            IEnumerable <Attribute> attrs = pi.GetCustomAttributes();

            foreach (Attribute a in attrs)
            {
                if (a is ValidationAttribute)
                {
                    ValidationAttribute va = (ValidationAttribute)a;
                    va.ErrorMessage = va.FormatErrorMessage(attr.DisplayName);
                    Type   attributeType = a.GetType();
                    string valName       = attributeType.Name.Replace("Attribute", string.Empty);
                    attr.Validations[valName] = va;
                }
            }
        }
コード例 #15
0
        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()));
        }
コード例 #16
0
        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));
                    }
                }
            }
        }
コード例 #17
0
        private (string validationRule, string errorMessage, string validationValue) GetValidationKey(string propName, ValidationAttribute validationAttribute)
        {
            string errorMessage = validationAttribute.ErrorMessage ?? validationAttribute.FormatErrorMessage(propName);

            if (validationAttribute is RegularExpressionAttribute reg)
            {
                return(Pattern, errorMessage, reg.Pattern);
            }
            if (validationAttribute is RequiredAttribute)
            {
                return(Required, errorMessage, null);
            }
            if (validationAttribute is CompareAttribute com)
            {
                return(Compare, errorMessage, com.OtherProperty.ToLowerFirstCharacter());
            }

            return(null, null, null);
        }
コード例 #18
0
        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);
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        /// <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);
        }
コード例 #21
0
        private Dictionary <string, object> GetPropertyValidationObject(Dictionary <string, object> atrs, string display, ValidationAttribute attr)
        {
            var msg = attr.FormatErrorMessage(display);

            if (attr is RequiredAttribute)
            {
                var atr = attr as RequiredAttribute;

                if (!atr.AllowEmptyStrings)
                {
                    atrs.Add("required", string.IsNullOrEmpty(msg) ? (object)true : msg);
                }

                goto End;
            }

            var attrs = (attr.TypeId as Type).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
                        .Where(d => !NotAttr.Contains(d.Name))
                        .Select(atr => new { atr.Name, val = atr.GetValue(attr) })
                        .Where(d => d.val != null)
                        .ToDictionary(d => d.Name.ToLower(), d => d.val);

            if (!string.IsNullOrEmpty(msg))
            {
                attrs["msg"] = msg;
            }

            //if (attr is DataTypeAttribute)
            //{
            //    var regex = (attr.TypeId as Type).GetField("_regex", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);

            //    if (regex != null) attrs["pattern"] = regex.GetValue(attr).ToString();
            //}

            var key = (attr.TypeId as Type).Name.Replace("Attribute", string.Empty).ToLower();

            atrs[key] = attrs.Any() ? (object)attrs : true;

            End : return(atrs);
        }
コード例 #22
0
        /// <summary>
        /// Validation of request when action is executing
        /// </summary>
        /// <param name="context"></param>
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            try
            {
                var value = context.ActionArguments[keyName];

                if (value != null)
                {
                    if (decode)
                    {
                        value = WebUtility.UrlDecode(value as string);
                    }

                    var attributes = new List <ValidationAttribute>()
                    {
                        validator
                    };
                    var results = new List <ValidationResult>();

                    bool isValid = Validator.TryValidateValue(value,
                                                              new ValidationContext(value),
                                                              results,
                                                              attributes);

                    if (!isValid)
                    {
                        context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        context.ModelState.AddModelError(keyName, results.First()?.ErrorMessage);
                        context.Result = new BadRequestObjectResult(context.ModelState);
                    }
                }
            }
            catch (KeyNotFoundException)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.ModelState.AddModelError(keyName, validator.FormatErrorMessage(keyName));
                context.Result = new BadRequestObjectResult(context.ModelState);
            }
            base.OnActionExecuting(context);
        }
コード例 #23
0
        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);
        }
コード例 #24
0
        public static string GetLocalizedString(ValidationAttribute attribute, string displayName)
        {
            string errorMsg = null;

            if (UseStringLocalizerProvider(attribute))
            {
                if (attribute is RangeAttribute)
                {
                    var attr = (RangeAttribute)attribute;
                    errorMsg = GetLocalizedString(attribute.ErrorMessage, displayName, attr.Minimum, attr.Maximum);
                }
                else if (attribute is RegularExpressionAttribute)
                {
                    var attr = (RegularExpressionAttribute)attribute;
                    errorMsg = GetLocalizedString(attribute.ErrorMessage, displayName, attr.Pattern);
                }
                else if (attribute is StringLengthAttribute)
                {
                    var attr = (StringLengthAttribute)attribute;
                    errorMsg = GetLocalizedString(attribute.ErrorMessage, displayName, attr.MinimumLength, attr.MaximumLength);
                }
                else if (attribute is MinLengthAttribute)
                {
                    var attr = (MinLengthAttribute)attribute;
                    errorMsg = GetLocalizedString(attribute.ErrorMessage, displayName, attr.Length);
                }
                else if (attribute is MaxLengthAttribute)
                {
                    var attr = (MaxLengthAttribute)attribute;
                    errorMsg = GetLocalizedString(attribute.ErrorMessage, displayName, attr.Length);
                }
                else
                {
                    errorMsg = GetLocalizedString(attribute.ErrorMessage);
                }
            }

            return(errorMsg ?? attribute.FormatErrorMessage(displayName));
        }
コード例 #25
0
            public override IEnumerable <ModelValidationResult> Validate(object container)
            {
                var context = new ValidationContext(container, null, null);
                var result  = attribute.GetValidationResult(Metadata.Model, context);

                if (result == null)
                {
                    yield break;
                }

                string tempErrorMsg;

                lock (attribute)
                {
                    attribute.ErrorMessage = this.errorMsg;
                    tempErrorMsg           = attribute.FormatErrorMessage(Metadata.GetDisplayName());
                    attribute.ErrorMessage = WorkaroundMarker;
                }
                yield return(new ModelValidationResult {
                    Message = tempErrorMsg
                });
            }
コード例 #26
0
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if (!(attribute is DataTypeAttribute))
            {
                attribute.ErrorMessage = attribute.FormatErrorMessage("{0}");

                if (attribute is MaxLengthAttribute)
                {
                    attribute.ErrorMessage = attribute.ErrorMessage.Replace((attribute as MaxLengthAttribute).Length.ToString(), "{1}");
                }
                else if (attribute is MinLengthAttribute)
                {
                    attribute.ErrorMessage = attribute.ErrorMessage.Replace((attribute as MinLengthAttribute).Length.ToString(), "{1}");
                }
                else if (attribute is StringLengthAttribute)
                {
                    attribute.ErrorMessage = attribute.ErrorMessage.Replace((attribute as StringLengthAttribute).MaximumLength.ToString(), "{1}").Replace((attribute as StringLengthAttribute).MinimumLength.ToString(), "{2}");
                }
            }

            return(originalProvider.GetAttributeAdapter(attribute, stringLocalizer));
        }
コード例 #27
0
        GuardFromAttribute <T>(
            T value,
            string paramName,
            string valueDescriptor,
            ValidationAttribute attribute)
        {
            var message =
                string.Format(
                    CultureInfo.InvariantCulture,
                    "{0} is invalid: {1}",
                    valueDescriptor,
                    attribute.FormatErrorMessage(paramName));

            if (attribute is RequiredAttribute && value == null)
            {
                throw new ArgumentNullException(paramName, message);
            }

            if (!attribute.IsValid(value))
            {
                throw new ArgumentException(message, paramName);
            }
        }
コード例 #28
0
            public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
            {
                attribute.ErrorMessage = attribute.FormatErrorMessage("{0}");

                return(_originalProvider.GetAttributeAdapter(attribute, stringLocalizer));
            }
コード例 #29
0
ファイル: ObjectValidator.cs プロジェクト: dbremner/nupattern
 private static string GetErrorMessage(ValidationAttribute validation, string displayName)
 {
     return(validation.FormatErrorMessage(displayName) ?? string.Format(Resources.Culture, Resources.ObjectValidator_ValidatorDefaultMessage, validation.GetType().Name));
 }
コード例 #30
0
 private static ClientRule CreateRule(ValidationAttribute attribute, RuleType ruleType)
 {
     return(new ClientRule(attribute.GetType().Name.ToLowerInvariant().Replace(Attribute, ""),
                           attribute.FormatErrorMessage(attribute.ErrorMessage), ruleType));
 }