示例#1
0
        public void ValidateProperty(T value, [CallerMemberName] string propertyName = null)
        {
            if (_validationAttributes == null)
            {
                return;
            }

            var context = new ValidationContext(this)
            {
                MemberName = propertyName
            };
            var validationErrors = new List <ValidationResult>();

            if (!DataValidator.TryValidateValue(value, context, validationErrors, _validationAttributes))
            {
                var errors = validationErrors.Select(error => error.ErrorMessage);
                _erros = errors.ToList();
            }
            else
            {
                _erros.Clear();
            }


            RaisePropertyChanged(nameof(ErrorMessage));
            RaisePropertyChanged(nameof(Errors));
            RaisePropertyChanged(nameof(HasErrors));
        }
        public void Setup()
        {
            var attribute = new RangeAttribute(5, 10);
            attribute.ErrorMessage = "test message";

            this.validator = new ValidationAttributeValidator(attribute);
        }
 public void Setup()
 {
     this.validator =
         new ValidationAttributeValidatorBuilder(
             new MemberAccessValidatorBuilderFactory(),
             ValidationFactory.DefaultCompositeValidatorFactory)
             .CreateValidator(typeof(TypeWithValidationAttributes));
 }
 public void TestInitialize()
 {
     ValidationFactory.SetDefaultConfigurationValidatorFactory(new ConfigurationValidatorFactory(new SystemConfigurationSource(false)));
     this.validator =
         new ValidationAttributeValidatorBuilder(
             new MemberAccessValidatorBuilderFactory(),
             ValidationFactory.DefaultCompositeValidatorFactory)
             .CreateValidator(typeof(TypeWithValidationAttributes));
 }
示例#5
0
        /// <summary>
        /// Wrapper for Validator.TryValidateObject
        /// </summary>
        /// <exception cref="System.ArgumentNullException">instance is null</exception>
        private static CombinedValues TryValidateObject(object objectToValidate)
        {
            ValidationContext       validationContext = new ValidationContext(objectToValidate, null, null);
            List <ValidationResult> validationResults = new List <ValidationResult>();
            bool isValid = MvcValidator.TryValidateObject(objectToValidate, validationContext, validationResults, true);

            return(new CombinedValues
            {
                IsValid = isValid,
                ValidationResults = validationResults
            });
        }
        public void TestDataAnnotations()
        {
            var sw = Stopwatch.StartNew();

            foreach (var item in _testData)
            {
                var ctx    = new ValidationContext(item, null, null);
                var errors = new List <ValidationResult>();
                DAValidator.TryValidateObject(item, ctx, errors);
            }

            sw.Stop();
            Assert.Inconclusive("DataAnnotations validated {0} objects in {1} ticks", TestDataCount, sw.ElapsedTicks);
        }
示例#7
0
        public static (bool isValid, ModelErrorDictionary modelErrors) IsValid(
            object model,
            IServiceProvider serviceProvider   = null,
            IDictionary <object, object> items = null)
        {
            var validationContext = new ValidationContext(model, serviceProvider, items);
            var validationResults = new List <ValidationResult>();

            SystemValidator.TryValidateObject(model, validationContext, validationResults, validateAllProperties: true);
            var(resultsWithMember, resultsWithoutMember) = validationResults.Fork(v => v.MemberNames.Count() > 0);

            var modelErrors = new ModelErrorDictionary(
                resultsWithMember
                .SelectMany(v => v.MemberNames.Select(m => (MemberName: m, ErrorMessage: v.ErrorMessage)))
                .ToLookup(t => t.MemberName)
                .ToDictionary(g => g.Key, g => g.Select(t => t.ErrorMessage)),
                resultsWithoutMember.Select(v => v.ErrorMessage));

            model.GetType().GetProperties().ForEach(pi =>
            {
                var attributes = pi.GetCustomAttributes(typeof(ValidateCustomBehaviourAttribute), false);
                attributes.ForEach(attribute =>
                {
                    if (attribute is ValidateEnumerableElementsAttribute)
                    {
                        ValidateEnumerableElements(model, serviceProvider, items, modelErrors, pi);
                        return;
                    }

                    var validateAgainstTypeIfAttribute = attribute as ValidateAgainstTypeIfAttribute;
                    if (validateAgainstTypeIfAttribute != null)
                    {
                        ValidateAgainstTypeIf(model, serviceProvider, items, modelErrors, pi, validateAgainstTypeIfAttribute);
                        return;
                    }

                    var validateAgainstTypeAttribute = attribute as ValidateAgainstTypeAttribute;
                    if (validateAgainstTypeAttribute != null)
                    {
                        ValidateAgainstType(model, serviceProvider, items, modelErrors, pi, validateAgainstTypeAttribute);
                        return;
                    }

                    throw new Exception("Unsupported ValidateCustomBehaviourAttribute");
                });
            });

            return(!modelErrors.HasErrors, modelErrors);
        }
        public static bool IsValid <TOptions>(this TOptions instance, IServiceProvider serviceProvider)
        {
            var results = Pooling.ListPool <ValidationResult> .Get();

            try
            {
                // FIXME: Use TK Validator
                var context = new ValidationContext(instance, serviceProvider, null);
                Validator.TryValidateObject(instance, context, results, true);
                return(results.Count == 0);
            }
            finally
            {
                Pooling.ListPool <ValidationResult> .Return(results);
            }
        }
        public static TOptions Validate <TOptions>(this TOptions instance, IServiceProvider serviceProvider)
        {
            var results = Pooling.ListPool <ValidationResult> .Get();

            try
            {
                var context = new ValidationContext(instance, serviceProvider, null);
                Validator.TryValidateObject(instance, context, results, true);
                if (results.Count == 0)
                {
                    return(instance);
                }

                var message = Pooling.StringBuilderPool.Scoped(sb =>
                {
                    sb.Append(typeof(TOptions).Name).Append(": ");
                    sb.AppendLine();

                    foreach (var result in results)
                    {
                        sb.Append(result.ErrorMessage);
                        sb.Append(" [");
                        var count = 0;
                        foreach (var field in result.MemberNames)
                        {
                            if (count != 0)
                            {
                                sb.Append(", ");
                            }

                            sb.Append(field);
                            count++;
                        }

                        sb.AppendLine("]");
                    }
                });

                throw new ValidationException(message);
            }
            finally
            {
                Pooling.ListPool <ValidationResult> .Return(results);
            }
        }
 public void Setup()
 {
     var factory =
         new ValidationAttributeValidatorFactory(new ValidationInstrumentationProvider(false, false, ""));
     this.validator = factory.CreateValidator<TypeWithValidationAttributes>();
 }
 public void Setup()
 {
     var factory =
         new ValidationAttributeValidatorFactory();
     this.validator = factory.CreateValidator<TypeWithValidationAttributes>();
 }
        public void Setup()
        {
            var attribute1 = new StringLengthAttribute(5);
            attribute1.ErrorMessage = "length";
            var attribute2 = new RegularExpressionAttribute("a*");
            attribute2.ErrorMessage = "regex";

            this.validator = new ValidationAttributeValidator(attribute1, attribute2);
        }
 public void Setup()
 {
     this.validator = new ValidationAttributeValidator();
 }
 public UserService()
 {
     _validator = new Validator<UserEntity>();
 }