コード例 #1
0
        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));
            }
        }
コード例 #2
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));
                    }
                }
            }
        }
コード例 #3
0
        private static void ValidAttribute(object item, PropertyInfo detailPropInfo, object customAttribute,
                                           out ValidationAttribute validationAttribute, out bool isValid)
        {
            validationAttribute = (ValidationAttribute)customAttribute;

            isValid = false;
            // 預設驗證的 Attributes。
            if (validationAttribute.GetType() == typeof(RequiredAttribute) || validationAttribute.GetType() ==
                typeof(RangeAttribute) ||
                validationAttribute.GetType() ==
                typeof(RegularExpressionAttribute) ||
                validationAttribute.GetType() ==
                typeof(StringLengthAttribute))
            {
                isValid = validationAttribute.IsValid(detailPropInfo.GetValue(item, BindingFlags.GetProperty, null,
                                                                              null, null));
            }

            // 自訂驗證的 Attributes。
            else
            {
                isValid = validationAttribute.IsValid(new object[]
                {
                    detailPropInfo.Name, detailPropInfo.GetValue(item, BindingFlags.GetProperty, null, null, null), item
                });
            }
        }
コード例 #4
0
        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));
            }
        }
コード例 #5
0
        private static bool IsValid(object dataEntity, string propertyName, Type propertyType, ValidationAttribute attribute)
        {
            object value;
            var    compareAttribute = attribute as CompareAttribute;

            if (compareAttribute != null)
            {
                value = new[] { dataEntity.Property(propertyName), dataEntity.Property(compareAttribute.PropertyName) };
            }
            else if (attribute is CustomAttribute)
            {
                value = new[] { new CustomValidatorContext(dataEntity, propertyName, attribute), dataEntity.Property(propertyName) };
            }
            else if (attribute is XmlSchemaAttribute && !string.IsNullOrEmpty(((XmlSchemaAttribute)attribute).SchemaProperty))
            {
                value = new[] { dataEntity.Property(propertyName), dataEntity.Property(((XmlSchemaAttribute)attribute).SchemaProperty) };
            }
            else
            {
                if (!dataEntity.PropertyTryGet(propertyName, out value) || Convert.IsDBNull(value))
                {
                    value = propertyType.GetDefault();
                }
            }
            return(attribute.IsValid(value));
        }
コード例 #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
ファイル: Validation.cs プロジェクト: liekiss/RayUtil
 private void ValidateAttribute(PropertyInfo property, ValidationAttribute attribute)
 {
     bool isValid = attribute.IsValid(property.GetValue(_target));
     if (isValid)
         return;
     _result.Add(new ValidationResult(GetErrorMessage(attribute)));
 }
コード例 #8
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");
            }
        }
コード例 #9
0
        public static bool IsValid(object obj, out string errorMsg)
        {
            StringBuilder           sb         = new StringBuilder();
            bool                    res        = true;
            var                     objType    = obj.GetType();
            var                     properties = objType.GetProperties();
            IEnumerable <Attribute> attris;

            foreach (var propertyInfo in properties)
            {
                object val = propertyInfo.GetValue(obj);
                attris = propertyInfo.GetCustomAttributes();
                foreach (var item in attris)
                {
                    if (item is ValidationAttribute)
                    {
                        ValidationAttribute validAttr = (ValidationAttribute)item;
                        if (!validAttr.IsValid(val))
                        {
                            res = false;
                            sb.AppendLine(validAttr.ErrorMessage);
                        }
                    }
                }
            }
            errorMsg = sb.ToString();
            return(res);
        }
コード例 #10
0
ファイル: ModelValidater.cs プロジェクト: dongwenbing/xili
 public void Validate(PropertyDescriptor pd, object value)
 {
     if (this.IsNeedValidate)
     {
         string key = string.Format(ModelValidater._proFormat, this.TypeName, pd.Name);
         ValidationAttribute[] attrs = ModelValidater._proValidation[key] as ValidationAttribute[];
         if (attrs == null || attrs.Length == 0)
         {
             return;
         }
         RequiredAttribute attRequired = attrs.FirstOrDefault((ValidationAttribute o) => o is RequiredAttribute) as RequiredAttribute;
         if (attRequired != null && !attRequired.IsValid(value))
         {
             throw new Exception(attRequired.ErrorMessage);
         }
         ValidationAttribute[] array = attrs;
         for (int i = 0; i < array.Length; i++)
         {
             ValidationAttribute attr = array[i];
             if (!attr.IsValid(value))
             {
                 throw new Exception(attr.ErrorMessage);
             }
         }
     }
 }
コード例 #11
0
        public static bool IsModelValid <TEntity>(this TEntity entity)
        {
            bool ret = null != entity;

            if (ret)
            {
                foreach (PropertyInfo pi in typeof(TEntity).GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    object value = pi.GetValue(entity);

                    foreach (var item in pi.GetCustomAttributes())
                    {
                        ValidationAttribute validation = item as ValidationAttribute;
                        if (null != validation)
                        {
                            if (!validation.IsValid(value))
                            {
                                ret = false;
                                goto Endfunc;
                            }
                        }
                    }
                }
            }

Endfunc:
            return(ret);
        }
コード例 #12
0
 /// <summary>
 /// Validates an attribute
 /// </summary>
 /// <param name="attribute"></param>
 /// <param name="i"></param>
 /// <exception cref="ArgumentException"></exception>
 public static void ValidateRangeAction(ValidationAttribute attribute, int i)
 {
     if (!attribute.IsValid(i))
     {
         throw new LocalDateRangeException();
     }
 }
コード例 #13
0
        public override bool IsValid(object value)
        {
            var optional = (IOptional)value;
            var isValid  = optional.MatchUntyped(o => _instance.IsValid(o), () => false);

            return(isValid);
        }
コード例 #14
0
 protected virtual void ValidateWithAttribute(ValidationAttribute attr, T value)
 {
     if (attr.IsValid(value))
     {
         return;
     }
     ValidationErrors.Add(attr.ErrorMessage);
 }
コード例 #15
0
 public override IEnumerable <ValidationError> Validate(ModelValidationContext context)
 {
     Precondition.Require(context, () => Error.ArgumentNull("context"));
     if (!_attribute.IsValid(context.Model))
     {
         yield return(new ValidationError(context.Member, _attribute.ErrorMessage));
     }
 }
コード例 #16
0
ファイル: Validation.cs プロジェクト: windygu/KQERP
        /// <summary>
        /// 验证特性
        /// </summary>
        /// <param name="property"></param>
        /// <param name="attribute"></param>
        private void ValidateAttribute(PropertyInfo property, ValidationAttribute attribute)
        {
            bool isValid = attribute.IsValid(property.GetValue(_target, null));

            if (!isValid)
            {
                _results.Add(new ValidationResult(GetErrorMessage(attribute)));
            }
        }
コード例 #17
0
        /// <summary>
        /// Determines whether the specified validation attribute is valid.
        /// </summary>
        /// <param name="validationAttribute">The validation attribute.</param>
        /// <param name="value">The value.</param>
        /// <returns>
        ///   <c>true</c> if the specified validation attribute is valid; otherwise, <c>false</c>.
        /// </returns>
        public bool IsValid(ValidationAttribute validationAttribute, object value)
        {
            if (!(validationAttribute is DataTypeAttribute))
            {
                return(validationAttribute.IsValid(value));
            }

            return(false);
        }
コード例 #18
0
        public bool IsValid(string propertyName)
        {
            if (!_mv.Properties.ContainsKey(propertyName))
            {
                return(false);
            }
            var value = _mv.Properties[propertyName];

            return(_attr.IsValid(value));
        }
コード例 #19
0
 public AttributeValidator(object objectToCheck, string propertyName, ValidationAttribute validationAttribute)
 {
     this.ValidationAttribute = validationAttribute;
     this.ErrorMessage        = validationAttribute.ErrorMessage;
     this.CheckForError       = () => !ValidationAttribute.IsValid(
         objectToCheck.GetType()
         .GetProperty(propertyName)
         .GetValue(objectToCheck));
     this.PropertyName = propertyName;
 }
コード例 #20
0
        private bool Validate(ValidationAttribute validationAttribute, string propertyName)
        {
            var propertyValue = this.propertyGetters[propertyName](this);

            if (IsConditionalValidationAttribute(validationAttribute))
            {
                return(validationAttribute.GetValidationResult(propertyValue, new ValidationContext(this)) == ValidationResult.Success);
            }

            return(validationAttribute.IsValid(propertyValue));
        }
コード例 #21
0
        protected virtual void ValidateValidator <TEntity>(List <ValidationIssue> validationIssues, TEntity entity, PropertyInfo property, ValidationAttribute validator)
        {
            var dataEntityProperty = typeof(TEntity).GetProperties().FirstOrDefault(p => p.Name == property.Name);
            var value = dataEntityProperty.GetValue(entity, null);

            //var value = property.GetValue(entity, null);
            if (!validator.IsValid(value))
            {
                validationIssues.Add(new ValidationIssue(property.Name, value, validator.ErrorMessage));
            }
        }
コード例 #22
0
        private void Validate(ValidationAttribute attrib, Property property)
        {
            if (SpecialCases(attrib, property))
            {
                return;
            }

            if (!attrib.IsValid(property.Value))
            {
                _errors.Add(new ValidationError(Map(attrib), property.Path, PropertiesExtractor.Extract(attrib)));
            }
        }
コード例 #23
0
ファイル: Validator2.cs プロジェクト: thornfieldhe/TAF
        /// <summary>
        /// 验证特性
        /// </summary>
        /// <param name="property">
        /// The property.
        /// </param>
        /// <param name="attribute">
        /// The attribute.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool ValidateAttribute(PropertyInfo property, ValidationAttribute attribute)
        {
            var isValid = attribute.IsValid(property.GetValue(_target));

            if (isValid)
            {
                return(true);
            }

            _result.Add(new ValidationResult(GetErrorMessage(attribute)));
            return(false);
        }
コード例 #24
0
ファイル: ValidationHelper.cs プロジェクト: hanxiaomeme/CERP
        /// <summary>
        /// 验证特性
        /// </summary>
        private static void ValidateAttribute(PropertyInfo property, ValidationAttribute attribute, object target, ValidationErrorCollection result)
        {
            bool isValid = attribute.IsValid(property.GetValue(target));

            if (isValid)
            {
                return;
            }
            result.Add(new ValidationError()
            {
                FieldName = property.Name, Message = GetErrorMessage(property.Name, attribute)
            });
        }
コード例 #25
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("");
 }
コード例 #26
0
        /// <summary>
        /// 验证方法
        /// </summary>
        /// <typeparam name="T"> </typeparam>
        /// <param name="obj"> </param>
        /// <param name="propertyName"> </param>
        /// <returns> </returns>
        public static string ValidateProperty <T>(this T obj, string propertyName) where T : NotifyPropertyBase
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                return(string.Empty);
            }
            Type         tp    = obj.GetType();
            PropertyInfo pi    = tp.GetProperty(propertyName);
            var          value = pi.GetValue(obj, null);

            object[] Attributes      = pi.GetCustomAttributes(false);
            string   strErrorMessage = "";

            if (Attributes != null && Attributes.Length > 0)
            {
                foreach (object attribute in Attributes)
                {
                    if (attribute is ValidationAttribute)
                    {
                        try
                        {
                            ValidationAttribute vAttribute = attribute as ValidationAttribute;
                            if (!vAttribute.IsValid(value))
                            {
                                if (vAttribute.ErrorMessageResourceType == typeof(Common.LanguageResource))
                                {
                                    strErrorMessage = Common.LangHelper.GetValue(vAttribute.ErrorMessageResourceName, vAttribute.ErrorMessage, "error");
                                }

                                if (String.IsNullOrWhiteSpace(strErrorMessage))
                                {
                                    if (vAttribute.ErrorMessageResourceType == typeof(Common.LanguageResource))
                                    {
                                        vAttribute.ErrorMessageResourceType = null;
                                    }
                                    strErrorMessage = !String.IsNullOrWhiteSpace(vAttribute.ErrorMessage) ? vAttribute.ErrorMessage : vAttribute.GetValidationResult(value, new ValidationContext(value, null, null)).ErrorMessage;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            ex.ToString();
                        }
                    }
                }
            }
            return(strErrorMessage);
        }
コード例 #27
0
ファイル: BaseModel.cs プロジェクト: AllenMaz/CommonLib
        /// <summary>
        /// 验证视图数据属性,可递归调用
        /// </summary>
        /// <param name="obj">视图数据对象</param>
        /// <param name="retMsg">返回消息</param>
        /// <returns></returns>
        public Message validate(BaseModel obj, bool ignoreRequired)
        {
            Message message = new Message();

            message.Success = true;

            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);;
            if (properties != null)
            {
                foreach (var property in properties)
                {
                    ///拥有的验证特性
                    object[] objs = property.GetCustomAttributes(typeof(ValidationAttribute), true);
                    foreach (var attrib in objs)
                    {
                        ValidationAttribute vAttrib = attrib as ValidationAttribute;
                        if (vAttrib != null)
                        {
                            //如果忽略校验必输项,则跳过OptionalRequired校验
                            if (vAttrib.GetType() == typeof(OptionalRequiredAttribute) && ignoreRequired)
                            {
                                continue;
                            }

                            ///验证
                            if (!vAttrib.IsValid(property.GetValue(obj, null)))
                            {
                                message.Content = vAttrib.ErrorMessage + "<br/><br/>";
                                message.Success = false;
                                return(message);
                            }
                        }
                        //也属于需要验证的对象
                        if (property.GetType() == typeof(BaseModel))
                        {
                            //递归验证
                            message = validate(property.GetValue(obj, null) as BaseModel, ignoreRequired);
                            if (!message.Success)
                            {
                                return(message);
                            }
                        }
                    }
                }
            }

            return(message);
        }
コード例 #28
0
        public bool IsValid()
        {
            if (string.IsNullOrEmpty(_product.Name))
            {
                Erros.Add("Product must have a name");
            }

            //else if (_product.Name.Any(s => !char.IsLetterOrDigit(s)))
            //    Erros.Add("Product name must have only letters or numbers");

            if (string.IsNullOrEmpty(_product.Description))
            {
                Erros.Add("Product must have a description");
            }

            if (string.IsNullOrEmpty(_product.Code))
            {
                Erros.Add("Product must have a code");
            }

            if (string.IsNullOrEmpty(_product.Brand))
            {
                Erros.Add("Product must have a brand");
            }

            if (string.IsNullOrEmpty(_product.ImageUrl))
            {
                Erros.Add("Product must have a image URL");
            }

            else if (!_validationAttribute.IsValid(_product.ImageUrl))
            {
                Erros.Add("Product must have valid image URL");
            }

            if (string.IsNullOrEmpty(_product.Type))
            {
                Erros.Add("Product must have a type");
            }

            if (_product.Price == 0)
            {
                Erros.Add("Product must have price higher than 0");
            }

            return(Erros.Count == 0);
        }
コード例 #29
0
 /// <summary>
 /// 使用特性对属性进行验证
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="property"></param>
 /// <param name="attribute"></param>
 private void ValidatePropertyAttribute(object entity, PropertyInfo property, ValidationAttribute attribute)
 {
     if (entity != null && property != null && attribute != null)
     {
         //找到该属性
         //注明:每一个函数都应当具有独立性.
         PropertyInfo currentProperty = entity.GetType().GetProperties().Where(p => p.Name == property.Name).FirstOrDefault();
         if (currentProperty != null)
         {
             var value = currentProperty.GetValue(entity, null);
             if (!attribute.IsValid(value))
             {
                 _modelState.Errors.Add(attribute.ErrorMessage);
             }
         }
     }
 }
コード例 #30
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));
        }
コード例 #31
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));
                    }
                }
            }
        }
コード例 #32
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);
        }