public void Should_localize_value()
 {
     using (new CultureScope("fr-fr")) {
         var orderValidator = new InlineValidator<Order>();
         orderValidator.RuleFor(x => x.Amount).GreaterThanOrEqualTo(1.2M).WithMessage("{ComparisonValue}");
         var result = orderValidator.Validate(new Order());
         var msg = result.Errors[0].ErrorMessage;
         msg.ShouldEqual("1,2");
     }
 }
		public void Uses_localized_name_from_display_attribute() {
			using (new CultureScope("en-us")) {
				var validator = new InlineValidator<Person2> {
					v => v.RuleFor(x => x.Name).NotNull().WithMessage("{PropertyName}")
				};

				var result = validator.Validate(new Person2());
				result.Errors[0].ErrorMessage.ShouldEqual("foo");

				using (new CultureScope("fr-FR")) {
					result = validator.Validate(new Person2());
					result.Errors[0].ErrorMessage.ShouldEqual("bar");
				}
			}
		}
		public void MemberNameValidatorSelector_returns_true_when_property_name_matches() {
			var validator = new InlineValidator<TestObject> {
				v => v.RuleFor(x => x.SomeProperty).NotNull()
			};

			var result = validator.Validate(new TestObject(), "SomeProperty");
			result.Errors.Count.ShouldEqual(1);
		}
		public void Infers_display_name_from_DisplayNameAttribute() {
			var validator = new InlineValidator<DisplayNameTestModel> {
				v => v.RuleFor(x => x.Name2).NotNull()
			};

			var result = validator.Validate(new DisplayNameTestModel());
			result.Errors.Single().ErrorMessage.ShouldEqual("'Bar' must not be empty.");
		}
		public void Does_not_validate_other_property_using_expression() {
			var validator = new InlineValidator<TestObject> {
				v => v.RuleFor(x => x.SomeOtherProperty).NotNull()
			};

			var result = validator.Validate(new TestObject(), x => x.SomeProperty);
			result.Errors.Count.ShouldEqual(0);
		}
		public void Nested_collection_for_null_property_should_not_throw_null_reference() {
			var validator = new InlineValidator<request>();
			validator.When(r => r.person != null, () => {
				validator.RuleForEach(x => x.person.NickNames).NotNull();
			});

			var result = validator.Validate(new request());
			result.Errors.Count.ShouldEqual(0);
		}
        public void Fails_for_ienumerable_that_doesnt_implement_ICollection()
        {
            var validator = new InlineValidator<TestModel> {
                v => v.RuleFor(x => x.Strings).NotEmpty()
            };

            var result = validator.Validate(new TestModel());
            result.IsValid.ShouldBeFalse();
        }
		public void Validates_nullable_property_with_overriden_name_when_selected() {

			var validator = new InlineValidator<TestObject> {
				v => v.RuleFor(x => x.SomeNullableProperty.Value)
				.GreaterThan(0)
				.When(x => x.SomeNullableProperty.HasValue)
				.OverridePropertyName("SomeNullableProperty")
			};

			var result = validator.Validate(new TestObject { SomeNullableProperty = 0 }, x => x.SomeNullableProperty);
			result.Errors.Count.ShouldEqual(1);
		}
		public void Falls_back_to_default_localization_key_when_error_code_key_not_found() {
			var originalLanguageManager = ValidatorOptions.Global.LanguageManager;
			ValidatorOptions.Global.LanguageManager = new CustomLanguageManager();
			ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("fr-FR");
			var validator = new InlineValidator<Person>();
			validator.RuleFor(x => x.Forename).NotNull().WithErrorCode("DoesNotExist");
			var result = validator.Validate(new Person());

			ValidatorOptions.Global.LanguageManager = originalLanguageManager;

			result.Errors[0].ErrorMessage.ShouldEqual("foo");
		}
        public void Applies_multiple_rulesets_to_rule()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleSet("First, Second", () => {
                validator.RuleFor(x => x.Forename).NotNull();
            });

            var result = validator.Validate(new Person(), ruleSet: "First");

            result.Errors.Count.ShouldEqual(1);

            result = validator.Validate(new Person(), ruleSet: "Second");
            result.Errors.Count.ShouldEqual(1);

            result = validator.Validate(new Person(), ruleSet: "Third");
            result.Errors.Count.ShouldEqual(0);

            result = validator.Validate(new Person());
            result.Errors.Count.ShouldEqual(0);
        }
示例#11
0
        public void Transforms_property_value()
        {
            var validator = new InlineValidator <Person>();

            validator.Transform(x => x.Surname, name => "foo" + name).Equal("foobar");

            var result = validator.Validate(new Person {
                Surname = "bar"
            });

            result.IsValid.ShouldBeTrue();
        }
        public void Nullable_enum_valid_when_value_specified()
        {
            var validator = new InlineValidator <Foo>();

            validator.RuleFor(x => x.Gender).IsInEnum();
            var result = validator.Validate(new Foo()
            {
                Gender = EnumGender.Male
            });

            result.IsValid.ShouldBeTrue();
        }
        public void Flags_enum_with_overlapping_flags_valid_when_using_bitwise_value()
        {
            var inlineValidator = new InlineValidator <FlagsEnumPoco>();

            inlineValidator.RuleFor(x => x.EnumWithOverlappingFlagsValue).IsInEnum();

            var poco = new FlagsEnumPoco();

            // test all combinations
            poco.EnumWithOverlappingFlagsValue = EnumWithOverlappingFlags.A | EnumWithOverlappingFlags.B;
            inlineValidator.Validate(poco).IsValid.ShouldBeTrue();

            poco.EnumWithOverlappingFlagsValue = EnumWithOverlappingFlags.B | EnumWithOverlappingFlags.C;
            inlineValidator.Validate(poco).IsValid.ShouldBeTrue();

            poco.EnumWithOverlappingFlagsValue = EnumWithOverlappingFlags.A | EnumWithOverlappingFlags.C;
            inlineValidator.Validate(poco).IsValid.ShouldBeTrue();

            poco.EnumWithOverlappingFlagsValue = EnumWithOverlappingFlags.A | EnumWithOverlappingFlags.B | EnumWithOverlappingFlags.C;
            inlineValidator.Validate(poco).IsValid.ShouldBeTrue();
        }
示例#14
0
        public void Executes_in_rule_in_ruleset_and_default()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleSet("First, Default", () => {
                validator.RuleFor(x => x.Forename).NotNull();
            });

            var result = validator.Validate(new Person(), v => v.IncludeRuleSets("First"));

            result.Errors.Count.ShouldEqual(1);
            AssertExecuted(result, "First");

            result = validator.Validate(new Person(), v => v.IncludeRuleSets("Second"));
            result.Errors.Count.ShouldEqual(0);
            AssertExecuted(result);

            result = validator.Validate(new Person());
            result.Errors.Count.ShouldEqual(1);
            AssertExecuted(result, "default");
        }
示例#15
0
        public virtual IList <ValidationFault> Validate(T obj)
        {
            var container = new Container(obj);
            var validator = new InlineValidator <Container>();
            var builder   = Validate(validator.RuleFor(x => x.Value).Must(x => true));
            var name      = OverrideName();

            if (!string.IsNullOrEmpty(name))
            {
                builder.WithName(name);
            }
            return(validator.Validate(container).Errors.ToValidationFaults());
        }
示例#16
0
        // ---

        protected override FluentValidation.Results.ValidationResult ValidateFields()
        {
            var v = new InlineValidator <ConfirmModel>()
            {
                CascadeMode = CascadeMode.StopOnFirstFailure
            };

            v.RuleFor(_ => _.RequestId)
            .Must(Common.ValidationRules.BeValidId).WithMessage("Invalid id")
            ;

            return(v.Validate(this));
        }
示例#17
0
        public void SearchDateTimeCriteriaValidatorNullTrueTest()
        {
            var value = new SearchDateCriteria()
            {
                SearchStartDate = "01.01.2020 10:10:10".GetUtcDateTime()
            };
            AbstractValidator <object> validator = new InlineValidator <object>();

            validator.RuleFor(x => x).ValidSearchDate();
            var result = validator.Validate(value).IsValid;

            result.Should().BeTrue();
        }
        public void Executes_in_rule_in_default_and_none()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleSet("First, Default", () => {
                validator.RuleFor(x => x.Forename).NotNull();
            });
            validator.RuleFor(x => x.Forename).NotNull();

            var result = validator.Validate(new Person(), ruleSet: "default");

            result.Errors.Count.ShouldEqual(2);
        }
示例#19
0
        public void Executes_in_rule_in_ruleset_and_default()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleSet("First, Default", () => {
                validator.RuleFor(x => x.Forename).NotNull();
            });

#pragma warning disable 618
            var result = validator.Validate(new Person(), ruleSet: "First");
            result.Errors.Count.ShouldEqual(1);
            AssertExecuted(result, "First");

            result = validator.Validate(new Person(), ruleSet: "Second");
            result.Errors.Count.ShouldEqual(0);
            AssertExecuted(result);
#pragma warning restore 618

            result = validator.Validate(new Person());
            result.Errors.Count.ShouldEqual(1);
            AssertExecuted(result, "default");
        }
示例#20
0
        // ---

        protected override FluentValidation.Results.ValidationResult ValidateFields()
        {
            var v = new InlineValidator <DpaCheckModel>()
            {
                CascadeMode = CascadeMode.StopOnFirstFailure
            };

            v.RuleFor(_ => _.Token)
            .Must(Common.ValidationRules.BeValidConfirmationTokenLength).WithMessage("Invalid length")
            ;;

            return(v.Validate(this));
        }
示例#21
0
        public void Transforms_property_value_with_propagated_original_object()
        {
            var validator = new InlineValidator <Person>();

            validator.Transform(x => x.Forename, (person, forename) => new { Nicks = person.NickNames, Name = forename })
            .Must(context => context.Nicks.Any(nick => nick == context.Name.ToLower()));

            var result = validator.Validate(new Person {
                NickNames = new[] { "good11", "peter" }, Forename = "Peter"
            });

            result.IsValid.ShouldBeTrue();
        }
示例#22
0
        // ---

        protected override FluentValidation.Results.ValidationResult ValidateFields()
        {
            var v = new InlineValidator <TfaModel>()
            {
                CascadeMode = CascadeMode.StopOnFirstFailure
            };

            v.RuleFor(_ => _.Code)
            .Must(Common.ValidationRules.BeValidTfaCode).WithMessage("Invalid format")
            ;

            return(v.Validate(this));
        }
示例#23
0
        public void Transforms_property_value_to_another_type()
        {
            var validator = new InlineValidator <Person>();

            validator.Transform(x => x.Surname, name => 1).GreaterThan(10);

            var result = validator.Validate(new Person {
                Surname = "bar"
            });

            result.IsValid.ShouldBeFalse();
            result.Errors[0].ErrorCode.ShouldEqual("GreaterThanValidator");
        }
		public void Uses_error_code_as_localization_key() {
			var originalLanguageManager = ValidatorOptions.Global.LanguageManager;
			ValidatorOptions.Global.LanguageManager = new CustomLanguageManager();

			using (new CultureScope("fr-FR")) {
				var validator = new InlineValidator<Person>();
				validator.RuleFor(x => x.Forename).NotNull().WithErrorCode("CustomKey");
				var result = validator.Validate(new Person());

				ValidatorOptions.Global.LanguageManager = originalLanguageManager;

				result.Errors[0].ErrorMessage.ShouldEqual("bar");
			}
		}
示例#25
0
        public ValidationResult Validate(Plan plan)
        {
            var validator = new InlineValidator <Plan>();

            validator.RuleFor(p => p.Name)
            .NotEmpty()
            .WithMessage("Nome é um campo obrigatório");

            validator.RuleFor(p => p.Price)
            .GreaterThan(0)
            .WithMessage("Preço é um campo obrigatório");

            return(validator.Validate(plan));
        }
示例#26
0
        public ValidationResult Validate(Product product)
        {
            var validator = new InlineValidator <Product>();

            validator.RuleFor(p => p.Name)
            .NotEmpty()
            .WithMessage("Nome é um campo obrigatório");

            validator.RuleFor(p => p.Cost)
            .GreaterThanOrEqualTo(0)
            .WithMessage("Custo deve ser um número positivo");

            return(validator.Validate(product));
        }
示例#27
0
        public void Failing_condition_should_prevent_multiple_components_running_and_not_throw()
        {
            // https://github.com/FluentValidation/FluentValidation/issues/1698
            var validator = new InlineValidator <Person>();

            validator.RuleForEach(x => x.Orders)
            .NotNull()
            .NotNull()
            .When(x => x.Orders.Count > 0);

            var result = validator.Validate(new Person());

            result.IsValid.ShouldBeTrue();
        }
示例#28
0
        public void HasLocalizedErrorMessageWithDefaultMessages()
        {
            var validator = new InlineValidator <AddNewUserAccountCommand>();

            validator.RuleFor(e => e.Email).NotEmpty().EmailAddress();
            var result = validator.Validate(new AddNewUserAccountCommand());

            result.IsValid.ShouldBeFalse();
            IsValidJson(result.Errors.First().ErrorMessage).ShouldBeTrue();

            var message = JsonConvert.DeserializeObject <LocalizedString>(result.Errors.First().ErrorMessage);

            message.En.ShouldNotBeEmpty();
            message.Fr.ShouldNotBeEmpty();
        }
        public void Trims_spaces()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleSet("First", () => {
                validator.RuleFor(x => x.Forename).NotNull();
            });
            validator.RuleSet("Second", () => {
                validator.RuleFor(x => x.Surname).NotNull();
            });

            var result = validator.Validate(new Person(), ruleSet: "First, Second");

            result.Errors.Count.ShouldEqual(2);
        }
        public void Creates_validator_using_context_from_property_value()
        {
            var personValidator = new InlineValidator <Person>();

            var normalOrderValidator = new InlineValidator <Order>();

            normalOrderValidator.RuleFor(x => x.Amount).GreaterThan(0);

            var freeOrderValidator = new InlineValidator <Order>();

            freeOrderValidator.RuleFor(x => x.Amount).Equal(0);

            personValidator.RuleForEach(x => x.Orders)
            .SetValidator((p, order) => order.ProductName == "FreeProduct" ? freeOrderValidator : normalOrderValidator);

            var result1 = personValidator.Validate(new Person()
            {
                Orders = new List <Order> {
                    new Order {
                        ProductName = "FreeProduct"
                    }
                }
            });

            result1.IsValid.ShouldBeTrue();

            var result2 = personValidator.Validate(new Person()
            {
                Orders = new List <Order> {
                    new Order()
                }
            });

            result2.IsValid.ShouldBeFalse();
            result2.Errors[0].ErrorCode.ShouldEqual("GreaterThanValidator");
        }
        public void Does_not_throw_InvalidCastException_when_using_RuleForEach()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleForEach(x => x.NickNames)
            .Must(x => false)
            .WithMessage((parent, name) => "x");

            var result = validator.Validate(new Person()
            {
                NickNames = new[] { "What" }
            });

            result.Errors.Single().ErrorMessage.ShouldEqual("x");
        }
        public void Validates_nullable_property_with_overriden_name_when_selected()
        {
            var validator = new InlineValidator <TestObject> {
                v => v.RuleFor(x => x.SomeNullableProperty.Value)
                .GreaterThan(0)
                .When(x => x.SomeNullableProperty.HasValue)
                .OverridePropertyName("SomeNullableProperty")
            };

            var result = validator.Validate(new TestObject {
                SomeNullableProperty = 0
            }, x => x.SomeNullableProperty);

            result.Errors.Count.ShouldEqual(1);
        }
        public void Vai_retornar_ano_modelo_invalido()
        {
            var caminhao = new Caminhao()
            {
                AnoModelo = DateTime.Now.Year + 2
            };
            var validator = new InlineValidator <Caminhao>();

            validarAnoModelo.AdicionarValidacao(validator);

            var resultado = validator.Validate(caminhao);

            Assert.IsFalse(resultado.IsValid);
            ContemErro(resultado, CodigoDoErroValidarAnoModelo01);
        }
        private void Validar(int ano)
        {
            var caminhao = new Caminhao()
            {
                AnoModelo = ano
            };
            var validator = new InlineValidator <Caminhao>();

            validarAnoModelo.AdicionarValidacao(validator);

            var resultado = validator.Validate(caminhao);

            Assert.IsTrue(resultado.IsValid);
            NaoContemErro(resultado, CodigoDoErroValidarAnoModelo01);
        }
示例#35
0
        public void Top_level_collection()
        {
            var v = new InlineValidator <IEnumerable <Order> >();

            v.RuleForEach(x => x).SetValidator(new OrderValidator());
            var orders = new List <Order> {
                new Order(),
                new Order()
            };

            var result = v.Validate(orders);

            result.Errors.Count.ShouldEqual(4);
            result.Errors[0].PropertyName.ShouldEqual("x[0].ProductName");
        }
示例#36
0
        public void Can_access_colletion_index()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleForEach(x => x.Orders).NotNull().WithMessage("{CollectionIndex}");
            var result = validator.Validate(new Person {
                Orders = new List <Order>()
                {
                    new Order(), null
                }
            });

            result.IsValid.ShouldBeFalse();
            result.Errors[0].ErrorMessage.ShouldEqual("1");
        }
示例#37
0
        public void Nested_conditions_Rule_For()
        {
            var validator = new InlineValidator <request>();

            validator.When(r => true, () => {
                validator.When(r => r.person?.NickNames?.Any() == true, () => {
                    validator.RuleFor(r => r.person.NickNames)
                    .Must(nn => true)
                    .WithMessage("Failed RuleFor");
                });
            });
            var result = validator.Validate(new request());

            result.IsValid.ShouldBeTrue();
        }
示例#38
0
        public void Can_use_cascade_with_RuleForEach()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleForEach(x => x.NickNames)
            .Cascade(CascadeMode.StopOnFirstFailure)
            .NotNull()
            .NotEqual("foo");

            var result = validator.Validate(new Person {
                NickNames = new string[] { null }
            });

            result.Errors.Count.ShouldEqual(1);
        }
 public void Nullable_enum_valid_when_property_value_is_null()
 {
     var validator = new InlineValidator<Foo>();
     validator.RuleFor(x => x.Gender).IsInEnum();
     var result = validator.Validate(new Foo());
     result.IsValid.ShouldBeTrue();
 }
        public void Flags_enum_invalid_when_using_outofrange_positive_value()
        {
            var inlineValidator = new InlineValidator<FlagsEnumPoco>();
            inlineValidator.RuleFor(x => x.SByteValue).IsInEnum();
            inlineValidator.RuleFor(x => x.ByteValue).IsInEnum();
            inlineValidator.RuleFor(x => x.Int16Value).IsInEnum();
            inlineValidator.RuleFor(x => x.UInt16Value).IsInEnum();
            inlineValidator.RuleFor(x => x.Int32Value).IsInEnum();
            inlineValidator.RuleFor(x => x.UInt32Value).IsInEnum();
            inlineValidator.RuleFor(x => x.Int64Value).IsInEnum();
            inlineValidator.RuleFor(x => x.UInt64Value).IsInEnum();

            var poco = new FlagsEnumPoco();
            poco.PopulateWithInvalidPositiveValues();

            var result = inlineValidator.Validate(poco);
            result.IsValid.ShouldBeFalse();
            result.Errors.SingleOrDefault(x => x.PropertyName == "ByteValue").ShouldNotBeNull();
            result.Errors.SingleOrDefault(x => x.PropertyName == "SByteValue").ShouldNotBeNull();
            result.Errors.SingleOrDefault(x => x.PropertyName == "Int16Value").ShouldNotBeNull();
            result.Errors.SingleOrDefault(x => x.PropertyName == "UInt16Value").ShouldNotBeNull();
            result.Errors.SingleOrDefault(x => x.PropertyName == "Int32Value").ShouldNotBeNull();
            result.Errors.SingleOrDefault(x => x.PropertyName == "UInt32Value").ShouldNotBeNull();
            result.Errors.SingleOrDefault(x => x.PropertyName == "Int64Value").ShouldNotBeNull();
            result.Errors.SingleOrDefault(x => x.PropertyName == "UInt64Value").ShouldNotBeNull();
        }
        public void Flags_enum_valid_when_using_bitwise_value()
        {
            var inlineValidator = new InlineValidator<FlagsEnumPoco>();
            inlineValidator.RuleFor(x => x.SByteValue).IsInEnum();
            inlineValidator.RuleFor(x => x.ByteValue).IsInEnum();
            inlineValidator.RuleFor(x => x.Int16Value).IsInEnum();
            inlineValidator.RuleFor(x => x.UInt16Value).IsInEnum();
            inlineValidator.RuleFor(x => x.Int32Value).IsInEnum();
            inlineValidator.RuleFor(x => x.UInt32Value).IsInEnum();
            inlineValidator.RuleFor(x => x.Int64Value).IsInEnum();
            inlineValidator.RuleFor(x => x.UInt64Value).IsInEnum();

            var poco = new FlagsEnumPoco();
            poco.PopulateWithValidValues();

            var result = inlineValidator.Validate(poco);
            result.IsValid.ShouldBeTrue();
        }
 public void Nullable_enum_valid_when_value_specified()
 {
     var validator = new InlineValidator<Foo>();
     validator.RuleFor(x => x.Gender).IsInEnum();
     var result = validator.Validate(new Foo() { Gender = EnumGender.Male });
     result.IsValid.ShouldBeTrue();
 }