public ObjectValidatorAttribute(string symbol, Type targetType) : base(symbol)
        {
            Assert.IsTrue(targetType.IsSubclassOf(typeof(ValidateAttribute)), MissingValidateAttributeWarning);

            TargetType      = targetType;
            TargetAttribute = (ValidateAttribute)Activator.CreateInstance(TargetType);
        }
        protected Dictionary <string, string> ValidateJs(object obj)
        {
            var attrs = from a in obj.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
                        where a.Name.StartsWith("On") && a.Name.EndsWith("Changed")
                        select new
            {
                Name = a.Name,
                Attr = a.GetCustomAttributes(true)
            };

            Dictionary <string, string> dic = new Dictionary <string, string>();
            string proname = string.Empty;

            foreach (var a in attrs)
            {
                ValidateAttribute b = a.Attr.FirstOrDefault(c => c is ValidateAttribute) as ValidateAttribute;
                if (b != null)
                {
                    proname = a.Name.Substring(2).Replace("Changed", "");
                    //var jsobj = ;
                    dic.Add(proname, (new { b.Default, b.ErrorMessage, b.IsRequired, b.Function }).ToJson().Replace("\"", "'"));
                }
            }
            return(dic);
        }
        private MethodInfo GetMethod(SerializedProperty property, ValidateAttribute validateAttribute)
        {
            var method = fieldInfo.DeclaringType.GetMethod(validateAttribute.Method, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            if (method != null)
            {
                if (method.ReturnType != typeof(bool))
                {
                    Debug.LogWarningFormat(_invalidMethodReturnWarning, property.propertyPath, validateAttribute.Method);
                }
                else if (!method.HasSignature(null))
                {
                    Debug.LogWarningFormat(_invalidMethodParametersWarning, property.propertyPath, validateAttribute.Method);
                }
                else
                {
                    return(method);
                }
            }
            else
            {
                Debug.LogWarningFormat(_missingMethodWarning, property.propertyPath, validateAttribute.Method, fieldInfo.DeclaringType.Name);
            }

            return(null);
        }
        internal static bool ValidateNumerics(PropertyInfo propertyInfo, ValidateAttribute validate, object value)
        {
            var success = true;
            var decimalRepresentationOfValidate = 0m;
            var decimalRepresentationOfObject   = 0m;

            success &= decimal.TryParse(value.ToString(), out decimalRepresentationOfObject);
            success &= decimal.TryParse(validate.Value.First().ToString(), out decimalRepresentationOfValidate);

            if (!success)
            {
                return(false);
            }

            switch (validate.Op)
            {
            case LogicalOperators.Equals:
                return(decimalRepresentationOfObject == decimalRepresentationOfValidate);

            case LogicalOperators.NotEquals:
                return(decimalRepresentationOfObject != decimalRepresentationOfValidate);

            case LogicalOperators.LesserThan:
                return(decimalRepresentationOfObject < decimalRepresentationOfValidate);

            case LogicalOperators.LesserThanOrEqual:
                return(decimalRepresentationOfObject <= decimalRepresentationOfValidate);

            case LogicalOperators.GreaterThan:
                return(decimalRepresentationOfObject > decimalRepresentationOfValidate);

            case LogicalOperators.GreaterThanOrEqual:
                return(decimalRepresentationOfObject >= decimalRepresentationOfValidate);

            case LogicalOperators.IsNotOneOf:
                return(!validate.Value.Any(v =>
                {
                    if (!decimal.TryParse(validate.Value.First().ToString(), out decimalRepresentationOfObject))
                    {
                        return false;
                    }

                    return decimalRepresentationOfObject == decimalRepresentationOfValidate;
                }));

            case LogicalOperators.IsOneOf:
                return(validate.Value.Any(v =>
                {
                    if (!decimal.TryParse(validate.Value.First().ToString(), out decimalRepresentationOfObject))
                    {
                        return false;
                    }

                    return decimalRepresentationOfObject == decimalRepresentationOfValidate;
                }));
            }

            throw new InvalidOperationException(string.Format("Validation for \"{0}\" of type \"{1}\", is not valid for numeric types.", propertyInfo.Name, validate.Op));
        }
        public ObjectTargetAttribute(string symbol, Type targetType) : base(symbol)
        {
            if (!targetType.IsSubclassOf(typeof(ValidateAttribute)))
            {
                throw new Exception("VObjectTarget must target an attribute deriving from VValidate");
            }

            TargetType      = targetType;
            TargetAttribute = Activator.CreateInstance(TargetType) as ValidateAttribute;
        }
        internal static bool ValidateNumerics(PropertyInfo propertyInfo, ValidateAttribute validate, object value)
        {
            var success = true;
            var decimalRepresentationOfValidate = 0m;
            var decimalRepresentationOfObject = 0m;

            success &= decimal.TryParse(value.ToString(), out decimalRepresentationOfObject);
            success &= decimal.TryParse(validate.Value.First().ToString(), out decimalRepresentationOfValidate);

            if (!success)
            {
                return false;
            }

            switch (validate.Op)
            {
                case LogicalOperators.Equals:
                    return decimalRepresentationOfObject == decimalRepresentationOfValidate;
                case LogicalOperators.NotEquals:
                    return decimalRepresentationOfObject != decimalRepresentationOfValidate;
                case LogicalOperators.LesserThan:
                    return decimalRepresentationOfObject < decimalRepresentationOfValidate;
                case LogicalOperators.LesserThanOrEqual:
                    return decimalRepresentationOfObject <= decimalRepresentationOfValidate;
                case LogicalOperators.GreaterThan:
                    return decimalRepresentationOfObject > decimalRepresentationOfValidate;
                case LogicalOperators.GreaterThanOrEqual:
                    return decimalRepresentationOfObject >= decimalRepresentationOfValidate;
                case LogicalOperators.IsNotOneOf:
                    return !validate.Value.Any(v =>
                        {
                            if (!decimal.TryParse(validate.Value.First().ToString(), out decimalRepresentationOfObject))
                            {
                                return false;
                            }

                            return decimalRepresentationOfObject == decimalRepresentationOfValidate;
                        });
                case LogicalOperators.IsOneOf:
                    return validate.Value.Any(v =>
                        {
                            if (!decimal.TryParse(validate.Value.First().ToString(), out decimalRepresentationOfObject))
                            {
                                return false;
                            }

                            return decimalRepresentationOfObject == decimalRepresentationOfValidate;
                        });
            }

            throw new InvalidOperationException(string.Format("Validation for \"{0}\" of type \"{1}\", is not valid for numeric types.", propertyInfo.Name, validate.Op));
        }
        public async Task For_OnActionExecutionAsync_When_ValidationFails_Then_BadRequestIsReturned()
        {
            // Arrange:
            var actionArguments = new List <object> {
                new Person()
            };

            var actionContextMock = TestsCommon.Utils.CreateActionExecutingContextMock();

            actionContextMock.Setup(x => x.ActionArguments.Values).Returns(actionArguments);

            IActionResult result = null;

            actionContextMock.SetupSet(context => context.Result = It.IsAny <IActionResult>())
            .Callback <IActionResult>(value => result            = value);
            var actionContext = actionContextMock.Object;

            var validator       = new TestAlwaysFailingPersonValidatorSync();
            var serviceProvider = Mock.Of <IServiceProvider>(x => x.GetService(It.IsAny <Type>()) == validator);
            var httpContext     = Mock.Of <HttpContext>(x => x.RequestServices == serviceProvider);

            actionContext.HttpContext = httpContext;

            var nextDelegateCalled = false;

            Task <ActionExecutedContext> Next()
            {
                nextDelegateCalled = true;
                var ctx = new ActionExecutedContext(actionContext, new List <IFilterMetadata>(), Mock.Of <Controller>());

                return(Task.FromResult(ctx));
            }

            // Act:
            var validateAttribute = new ValidateAttribute {
                TypeToValidate = typeof(Person)
            };
            await validateAttribute.OnActionExecutionAsync(actionContextMock.Object, Next);

            // Assert:
            nextDelegateCalled.Should().BeFalse();
            result.Should().BeOfType <BadRequestObjectResult>();
            var validationResult = (ValidationResult)((BadRequestObjectResult)result).Value;

            validationResult.Failure.Should().BeTrue();
            validationResult.Properties[0].PropertyName.Should().Be("FirstName");
            validationResult.Properties[1].PropertyName.Should().Be("LastName");
        }
        internal static bool ValidateNonNumerics(PropertyInfo propertyInfo, ValidateAttribute validate, object value)
        {
            switch (validate.Op)
            {
                case LogicalOperators.Equals:
                    return value.Equals(validate.Value.First());
                case LogicalOperators.NotEquals:
                    return !value.Equals(validate.Value.First());
                case LogicalOperators.IsOneOf:
                    return validate.Value.Any(value.Equals);
                case LogicalOperators.IsNotOneOf:
                    return !validate.Value.Any(value.Equals);
            }

            throw new InvalidOperationException(string.Format("Validation for \"{0}\" of type \"{1}\", is not valid for non numeric types.", propertyInfo.Name, validate.Op));
        }
        internal static bool ValidateSingle(PropertyInfo propertyInfo, ValidateAttribute validate, object value)
        {
            if (value == null)
            {
                return(true);
            }

            if (validate.Validator != null && typeof(IValidator).IsAssignableFrom(validate.Validator))
            {
                var validator = (IValidator)Activator.CreateInstance(validate.Validator);
                return(validator.Validate(value));
            }

            return(value.IsNumeric()
                ? ValidateNumerics(propertyInfo, validate, value)
                : ValidateNonNumerics(propertyInfo, validate, value));
        }
Exemple #10
0
        /// <summary>
        /// 校验数据是否合法
        /// </summary>
        /// <param name="validate">校验规则</param>
        /// <param name="value">待校验值</param>
        /// <param name="caption">描述</param>
        /// <returns></returns>
        private static ValidateResult Validate(ValidateAttribute validate, object value, CaptionAttribute caption)
        {
            ValidateResult result = new ValidateResult();

            if (!validate.Validate(value))
            {
                result.IsSuccess = false;
                if (caption == null)
                {
                    result.ErrorMessage = validate.GetErrorMessage();
                }
                else
                {
                    result.ErrorMessage = validate.GetErrorMessage(caption.Name);
                }
            }
            return(result);
        }
        internal static bool ValidateNonNumerics(PropertyInfo propertyInfo, ValidateAttribute validate, object value)
        {
            switch (validate.Op)
            {
            case LogicalOperators.Equals:
                return(value.Equals(validate.Value.First()));

            case LogicalOperators.NotEquals:
                return(!value.Equals(validate.Value.First()));

            case LogicalOperators.IsOneOf:
                return(validate.Value.Any(value.Equals));

            case LogicalOperators.IsNotOneOf:
                return(!validate.Value.Any(value.Equals));
            }

            throw new InvalidOperationException(string.Format("Validation for \"{0}\" of type \"{1}\", is not valid for non numeric types.", propertyInfo.Name, validate.Op));
        }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (property.objectReferenceValue != null)
        {
            UnityEngine.Object serializeObj      = property.objectReferenceValue;
            ValidateAttribute  validateAttribute = attribute as ValidateAttribute;
            Type   validType     = validateAttribute.ValidType;
            Type   objType       = serializeObj.GetType();
            Type[] objInterfaces = objType.GetInterfaces();
            Type   interfaceType = objInterfaces.FirstOrDefault(x => x == validType);

            if (interfaceType == null)
            {
                Debug.LogError(serializeObj + " doesn`t inherit valid interface");
                property.objectReferenceValue = null;
            }
            property.serializedObject.ApplyModifiedProperties();
        }
        EditorGUI.PropertyField(position, property, label);
    }
        public void For_OnActionExecutionAsync_When_AsyncValidatorProvidedAndThereIsNoValidateAction_Then_ExceptionIsThrown()
        {
            // Arrange:
            var actionArguments = new List <object> {
                new Person()
            };

            var actionContextMock = TestsCommon.Utils.CreateActionExecutingContextMock();

            actionContextMock.Setup(x => x.ActionArguments.Values).Returns(actionArguments);

            IActionResult result = null;

            actionContextMock.SetupSet(context => context.Result = It.IsAny <IActionResult>())
            .Callback <IActionResult>(value => result            = value);
            var actionContext = actionContextMock.Object;

            var validator       = new TestPersonValidatorAsync(); // Async validator should return null Validate() method
            var serviceProvider = Mock.Of <IServiceProvider>(x => x.GetService(It.IsAny <Type>()) == validator);
            var httpContext     = Mock.Of <HttpContext>(x => x.RequestServices == serviceProvider);

            actionContext.HttpContext = httpContext;

            Task <ActionExecutedContext> Next()
            {
                var ctx = new ActionExecutedContext(actionContext, new List <IFilterMetadata>(), Mock.Of <Controller>());

                return(Task.FromResult(ctx));
            }

            // Act & Assert:
            var validateAttribute = new ValidateAttribute {
                TypeToValidate = typeof(Person)
            };
            var exception = Assert.ThrowsAsync <InvalidOperationException>(() =>
                                                                           validateAttribute.OnActionExecutionAsync(actionContextMock.Object, Next));

            exception.Message.Should().Contain("No sync validate method for");
        }
        public async Task For_OnActionExecutionAsync_When_ValidationSuccesses_Then_HttpRequestPipelineIsContinued()
        {
            // Arrange:
            var actionArguments = new List <object> {
                new Person()
            };

            var actionContextMock = TestsCommon.Utils.CreateActionExecutingContextMock();

            actionContextMock.Setup(x => x.ActionArguments.Values).Returns(actionArguments);
            var actionContext = actionContextMock.Object;

            var validator       = new TestPersonValidatorSync();
            var serviceProvider = Mock.Of <IServiceProvider>(x => x.GetService(It.IsAny <Type>()) == validator);
            var httpContext     = Mock.Of <HttpContext>(x => x.RequestServices == serviceProvider);

            actionContext.HttpContext = httpContext;

            var nextDelegateCalled = false;

            Task <ActionExecutedContext> Next()
            {
                var ctx = new ActionExecutedContext(actionContext, new List <IFilterMetadata>(), Mock.Of <Controller>());

                nextDelegateCalled = true;
                return(Task.FromResult(ctx));
            }

            // Act:
            var validateAttribute = new ValidateAttribute {
                TypeToValidate = typeof(Person)
            };
            await validateAttribute.OnActionExecutionAsync(actionContextMock.Object, Next);

            // Assert:
            nextDelegateCalled.Should().BeTrue();
        }
Exemple #15
0
        /// <summary>
        /// 校验对象属性值是否合法
        /// </summary>
        /// <param name="obj">待校验对象</param>
        /// <returns></returns>
        public static ValidateResult Validate(this IValidate obj)
        {
            ValidateResult result = new ValidateResult();

            PropertyInfo[] infos = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo p in infos)
            {
                //获取数据校验特性。
                Attribute[] attrs = Attribute.GetCustomAttributes(p, typeof(ValidateAttribute), false);
                if (attrs.Length <= 0)
                {
                    continue;
                }

                //获取名称描述特性
                CaptionAttribute caption = Attribute.GetCustomAttribute(p, typeof(CaptionAttribute), false) as CaptionAttribute;
                object           value   = p.GetValue(obj);

                foreach (Attribute attr in attrs)
                {
                    ValidateAttribute validate = attr as ValidateAttribute;
                    if (validate == null)
                    {
                        continue;
                    }

                    result = Validate(validate, value, caption);
                    if (!result.IsSuccess)
                    {
                        return(result);
                    }
                }
            }
            return(result);
        }
        internal static bool ValidateSingle(PropertyInfo propertyInfo, ValidateAttribute validate, object value)
        {
            if (value == null)
            {
                return true;
            }

            if (validate.Validator != null && typeof(IValidator).IsAssignableFrom(validate.Validator))
            {
                var validator = (IValidator) Activator.CreateInstance(validate.Validator);
                return validator.Validate(value);
            }

            return value.IsNumeric()
                ? ValidateNumerics(propertyInfo, validate, value)
                : ValidateNonNumerics(propertyInfo, validate, value);
        }