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");
     }
 }
Пример #2
0
        public void CreditCard_error_string_is_correct()
        {
            // Arrange
            var validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.StringProp).CreditCard();

            // Act
            var result = validator.Validate(new TestDto
            {
                StringProp = "1111"
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""creditCard""}}");
        }
Пример #3
0
        public async Task Multiple_rules_in_chain_with_childvalidator_shouldnt_reuse_accessor_async()
        {
            var validator     = new InlineValidator <Person>();
            var addrValidator = new InlineValidator <Address>();

            addrValidator.RuleFor(x => x.Line1).MustAsync((l, t) => Task.FromResult(l != null));

            validator.RuleFor(x => x.Address).SetValidator(addrValidator)
            .MustAsync((a, t) => Task.FromResult(a != null));

            var result = await validator.ValidateAsync(new Person()
            {
                Address = new Address()
            });

            result.Errors.Count.ShouldEqual(1);
        }
        public void Custom_state_comparer_check()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleFor(x => x.Surname).NotNull().WithState(x => "Test" + 123);
            var result = validator.TestValidate(new Person());

            // Throws without comparer.
            Assert.Throws <ValidationTestException>(() => {
                result.ShouldHaveValidationErrorFor(x => x.Surname)
                .WithCustomState("test123");
            });

            // Doesn't throw with comparer.
            result.ShouldHaveValidationErrorFor(x => x.Surname)
            .WithCustomState("test123", StringComparer.OrdinalIgnoreCase);
        }
        public void Can_use_indexer_in_string_message_inverse()
        {
            var validator      = new InlineValidator <Person>();
            var orderValidator = new InlineValidator <Order>();

            orderValidator.RuleFor(x => x.ProductName).Null();
            validator.RuleForEach(x => x.Orders).SetValidator(orderValidator);

            var model = new Person {
                Orders = new List <Order> {
                    new Order()
                }
            };
            var result = validator.TestValidate(model);

            result.ShouldNotHaveValidationErrorFor("Orders[0].ProductName");
        }
Пример #6
0
        public void Regex_error_string_is_correct()
        {
            // Arrange
            var validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.StringProp).Matches(@"\d+");

            // Act
            var result = validator.Validate(new TestDto
            {
                StringProp = "a",
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""regex""}}");
        }
Пример #7
0
        public void NotNull_error_string_is_correct()
        {
            // Arrange
            var validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.StringProp).NotNull();

            // Act
            var result = validator.Validate(new TestDto
            {
                StringProp = null
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""notEmpty""}}");
        }
Пример #8
0
        public void Multiple_rules_in_chain_with_childvalidator_shouldnt_reuse_accessor()
        {
            var validator     = new InlineValidator <Person>();
            var addrValidator = new InlineValidator <Address>();

            addrValidator.RuleFor(x => x.Line1).NotNull();

            validator.RuleFor(x => x.Address).SetValidator(addrValidator)
            .Must(a => a != null);

            var result = validator.Validate(new Person()
            {
                Address = new Address()
            });

            result.Errors.Count.ShouldEqual(1);
        }
Пример #9
0
        public void New_Custom_When_property_name_omitted_infers_property_name_nested()
        {
            var addressValidator = new InlineValidator <Address>();

            addressValidator.RuleFor(x => x.Line1).Custom((x, ctx) => {
                ctx.AddFailure("Error");
            });

            validator.RuleFor(x => x.Address)
            .SetValidator(addressValidator);

            var result = validator.Validate(new Person {
                Address = new Address()
            });

            result.Errors.Single().PropertyName.ShouldEqual("Address.Line1");
        }
Пример #10
0
                public static IValidator <PaymentMehtodsSection> GetValidator()
                {
                    var v = new InlineValidator <PaymentMehtodsSection>()
                    {
                        CascadeMode = CascadeMode.Continue
                    };

                    v.RuleFor(_ => _.EthDepositMinEther).GreaterThan(0);
                    v.RuleFor(_ => _.EthDepositMaxEther).GreaterThan(0);
                    v.RuleFor(_ => _.EthWithdrawMinEther).GreaterThan(0);
                    v.RuleFor(_ => _.EthWithdrawMaxEther).GreaterThan(0);

                    v.RuleFor(_ => _.CreditCardDepositMinUsd).GreaterThan(0);
                    v.RuleFor(_ => _.CreditCardDepositMaxUsd).GreaterThan(0);
                    v.RuleFor(_ => _.CreditCardWithdrawMinUsd).GreaterThan(0);
                    v.RuleFor(_ => _.CreditCardWithdrawMinUsd).GreaterThan(0);

                    return(v);
                }
Пример #11
0
        public DoublesCompetitionResultEntryCommandValidator()
        {
            var validator       = new InlineValidator <CompetitionResultEntryPlayerModel>();
            var playerValidator = new PlayerRegistrationModelValidator();

            validator.RuleFor(x => x.Player1).NotNull();
            validator.RuleFor(x => x.Player1).SetValidator(playerValidator);
            validator.RuleFor(x => x.Player2).NotNull();
            validator.RuleFor(x => x.Player2).SetValidator(playerValidator);
            validator.RuleFor(x => x.Player3).Null();
            validator.RuleFor(x => x.Player4).Null();
            validator.RuleFor(x => x.Score).SetValidator(new CompetitionResultEntryGameScoreModelValidator());

            this.RuleFor(x => x.ResultEntry).NotNull();
            this.RuleFor(x => x.ResultEntry).SetValidator(new CompetitionResultEntryModelValidator(validator));
        }
Пример #12
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(), ruleSet: "First");

            result.Errors.Count.ShouldEqual(1);

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

            result = validator.Validate(new Person());
            result.Errors.Count.ShouldEqual(1);
        }
Пример #13
0
            public void Should_be(string path, bool expectedOutcome)
            {
                // Arrange
                var validator = new InlineValidator <Model>();

                validator
                .RuleFor(x => x.Path)
                .Uri(UriKind.Relative);
                var model = new Model {
                    Path = path
                };

                // Act
                var result = validator.Validate(model);

                // Assert
                Assert.Equal(expectedOutcome, result.IsValid);
            }
        public void Test_custom_state_with_concatenated_string()
        {
            var validator = new InlineValidator <Person>();

            validator.RuleFor(x => x.Surname).NotNull().WithState(x => "Test" + 123);
            var result = validator.TestValidate(new Person());

            // String concatenated with integer means a different string reference is created:

            /*
             *      object s1 = "Test" + 123.ToString();
             *      object s2 = "Test123";
             *      bool check1 = s1 == s2; // False
             */
            // Test to ensure that this scenario is handled properly.
            result.ShouldHaveValidationErrorFor(x => x.Surname)
            .WithCustomState("Test123");
        }
Пример #15
0
        public void GreaterThan_to_error_string_is_correct()
        {
            // Arrange
            const int expectedNumber = 100;
            var       validator      = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.IntProp).GreaterThan(expectedNumber);

            // Act
            var result = validator.Validate(new TestDto
            {
                IntProp = expectedNumber - 1,
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""greaterThan"",""comparisonValue"":""{expectedNumber}""}}");
        }
        public void Validates_collection_several_levels_deep()
        {
            var validator = new TestValidator {
                v => v.RuleFor(x => x.Surname).NotNull(),
                v => v.RuleForEach(x => x.Orders).SetValidator(y => new OrderValidator(y))
            };

            var rootValidator = new InlineValidator <Tuple <Person, object> >();

            rootValidator.RuleFor(x => x.Item1).SetValidator(validator);

            var results = rootValidator.Validate(Tuple.Create(person, new object()));

            results.Errors.Count.ShouldEqual(3);

            results.Errors[1].PropertyName.ShouldEqual("Item1.Orders[0].ProductName");
            results.Errors[2].PropertyName.ShouldEqual("Item1.Orders[2].ProductName");
        }
        public CreateTriplesRegistrationCommandValidator()
        {
            this.RuleFor(x => x.Registration).NotNull();
            this.RuleFor(x => x.Registration).SetValidator(new CompetitionRegistrationModelValidator());

            var validator       = new InlineValidator <PlayersRegistrationModel>();
            var playerValidator = new PlayerRegistrationModelValidator();

            validator.RuleFor(x => x.Player1).NotNull();
            validator.RuleFor(x => x.Player1).SetValidator(playerValidator);
            validator.RuleFor(x => x.Player2).NotNull();
            validator.RuleFor(x => x.Player2).SetValidator(playerValidator);
            validator.RuleFor(x => x.Player3).NotNull();
            validator.RuleFor(x => x.Player3).SetValidator(playerValidator);
            validator.RuleFor(x => x.Player4).Null();
            this.RuleForEach(x => x.Registration.Players).SetValidator(validator);
        }
Пример #18
0
        public void ScalePrecision_error_string_is_correct()
        {
            // Arrange
            const int expectedPrecision = 4;
            const int expectedScale     = 2;
            var       validator         = new InlineValidator <ScalePrecisionDto>();

            validator.RuleFor(x => x.DecimalProp).ScalePrecision(expectedScale, expectedPrecision);

            // Act
            var result = validator.Validate(new ScalePrecisionDto
            {
                DecimalProp = 123.45678m
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""scalePrecision"",""expectedPrecision"":""{expectedPrecision}"",""expectedScale"":""{expectedScale}"",""digits"":""3"",""actualScale"":""5""}}");
        }
Пример #19
0
        public async Task Collection_async_RunsTasksSynchronously()
        {
            var result         = new List <bool>();
            var validator      = new InlineValidator <Person>();
            var orderValidator = new InlineValidator <Order>();

            orderValidator.RuleFor(x => x.ProductName).MustAsync((x, token) => {
                return(ExclusiveDelay(1)
                       .ContinueWith(t => result.Add(t.Result))
                       .ContinueWith(t => true));
            });

            validator.RuleFor(x => x.Orders).SetCollectionValidator(orderValidator);

            await validator.ValidateAsync(person);

            Assert.NotEmpty(result);
            Assert.All(result, Assert.True);
        }
        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();
        }
Пример #21
0
        public void MinLength_error_string_is_correct()
        {
            // Arrange
            const int minLength = 5;
            const int entered   = minLength - 1;
            var       validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.StringProp).MinimumLength(minLength);

            // Act
            var result = validator.Validate(new TestDto
            {
                StringProp = new string('a', entered),
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""minLength"",""minLength"":""{minLength}"",""entered"":""{entered}""}}");
        }
Пример #22
0
        public void Uses_explicit_ruleset()
        {
            var addressValidator = new InlineValidator <Address>();

            addressValidator.RuleSet("ruleset1", () => {
                addressValidator.RuleFor(x => x.Line1).NotNull();
            });
            addressValidator.RuleFor(x => x.Line2).NotNull();
            var validator = new InlineValidator <Person>();

            validator.RuleFor(x => x.Address).SetValidator(addressValidator, ruleSets: "ruleset1");

            var result = validator.Validate(new Person {
                Address = new Address()
            });

            result.Errors.Count.ShouldEqual(1);
            result.Errors[0].PropertyName.ShouldEqual("Address.Line1");
        }
Пример #23
0
        public void Equal_error_string_is_correct()
        {
            // Arrange
            const int target    = 3;
            const int entered   = target + 1;
            var       validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.IntProp).Equal(target);

            // Act
            var result = validator.Validate(new TestDto
            {
                IntProp = entered
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""equal"",""comparisonValue"":""{target}""}}");
        }
Пример #24
0
        public void LessThan_error_string_is_correct()
        {
            // Arrange
            const int limit     = 3;
            const int entered   = limit;
            var       validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.IntProp).LessThan(limit);

            // Act
            var result = validator.Validate(new TestDto
            {
                IntProp = entered
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""lessThan"",""comparisonValue"":""{limit}""}}");
        }
Пример #25
0
        public void ExactLength_error_string_is_correct()
        {
            // Arrange
            const int limit     = 3;
            const int entered   = limit + 1;
            var       validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.StringProp).Length(limit);

            // Act
            var result = validator.Validate(new TestDto
            {
                StringProp = new string('a', entered),
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""exactLength"",""length"":""{limit}"",""entered"":""{entered}""}}");
        }
Пример #26
0
        public void SimpleInclusiveBetween_error_string_is_correct()
        {
            // Arrange
            const int min       = 2;
            const int max       = 4;
            var       validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.IntProp)
            .InclusiveBetween(min, max)
            .WithErrorCode("InclusiveBetween_Simple");

            // Act
            var result = validator.Validate(new TestDto
            {
                IntProp = max + min,
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe($@"{{""key"":""simpleInclusiveBetween"",""from"":""{min}"",""to"":""{max}""}}");
        }
Пример #27
0
        public void SimpleMaxLength_error_string_is_correct()
        {
            // Arrange
            const int maxLength = 2;
            const int entered   = maxLength + 1;
            var       validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.StringProp)
            .MaximumLength(maxLength)
            .WithErrorCode("MaximumLength_Simple");

            // Act
            var result = validator.Validate(new TestDto
            {
                StringProp = new string('a', entered),
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe($@"{{""key"":""simpleMaxLength"",""maxLength"":""{maxLength}""}}");
        }
        public void Should_work_with_top_level_collection_validator_and_overriden_name()
        {
            var personValidator = new InlineValidator <Person>();

            personValidator.RuleFor(x => x.Surname).NotNull();

            var validator = new InlineValidator <List <Person> >();

            validator.RuleForEach(x => x).SetValidator(personValidator).OverridePropertyName("test");


            var results = validator.Validate(new List <Person> {
                new Person(), new Person(), new Person {
                    Surname = "Bishop"
                }
            });

            results.Errors.Count.ShouldEqual(2);
            results.Errors[0].PropertyName.ShouldEqual("test[0].Surname");
        }
Пример #29
0
        public void ExclusiveBetween_error_string_is_correct()
        {
            // Arrange
            const int lower   = 3;
            const int upper   = 5;
            const int entered = upper + 1;

            var validator = new InlineValidator <TestDto>();

            validator.RuleFor(x => x.IntProp).ExclusiveBetween(lower, upper);

            // Act
            var result = validator.Validate(new TestDto
            {
                IntProp = entered,
            });

            // Assert
            result.Errors[0].ErrorMessage.ShouldBe(
                $@"{{""key"":""exclusiveBetween"",""from"":""{lower}"",""to"":""{upper}"",""entered"":""{entered}""}}");
        }
Пример #30
0
        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();
        }
Пример #31
0
        public async Task Resets_state_correctly_between_rules_async()
        {
            var v = new InlineValidator <Person>();

            v.RuleForEach(x => x.NickNames).NotNull();
            v.RuleFor(x => x.Forename).NotNull();

            // The ValidationContext is reinitialized for each item in the collection
            // Specifically, the PropertyChain is reset and modified.
            // After the collection has been validated, the PropertyChain should be reset to its original value.
            // We can test this by checking the final output of the property names for subsequent rules after the RuleForEach.
            var result = await v.ValidateAsync(new Person()
            {
                NickNames = new[] { null, "Foo", null }, Forename = null
            });

            result.Errors.Count.ShouldEqual(3);
            result.Errors[0].PropertyName.ShouldEqual("NickNames[0]");
            result.Errors[1].PropertyName.ShouldEqual("NickNames[2]");
            result.Errors[2].PropertyName.ShouldEqual("Forename");
        }
 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 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_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 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();
        }