public void Should_be_valid_when_condition_returns_true_using_instance_property()
        {
            var validator = new CustomValidator<Person, int>((p, v) => p.Age % v == 0);

            var person = new Person {Age = 16};
            Assert.That(validator.Validate(person, 4), Is.True);
        }
        public void Should_be_invalid_when_value_is_lower_using_instance_property()
        {
            var validator = new GreaterOrEqualToValidator<Person, int>(p => p.Age);

            var person = new Person { Age = 18 };
            Assert.That(validator.Validate(person, 16), Is.False);
        }
        public void Should_be_valid_when_value_is_greater_using_instance_property()
        {
            var validator = new GreaterThanValidator<Person, int>(p => p.Age);

            var person = new Person {Age = 18};
            Assert.That(validator.Validate(person, 21), Is.True);
        }
        public void Should_be_valid_when_values_are_equal_using_instance_property()
        {
            var validator = new EqualValidator<Person, int>(p => p.Age);

            var person = new Person {Age = 15};
            Assert.That(validator.Validate(person, 15), Is.True);
        }
        public void Should_be_invalid_when_length_is_lower_than_min_value_using_instance_property()
        {
            var validator = new LengthValidator<Person>(p => p.Name.Length, p => p.Age);

            var person = new Person { Name = "Bob", Age = 8 };
            Assert.That(validator.Validate(person, "AB"), Is.False);
        }
        public void Should_be_invalid_when_value_is_equal_using_instance_property()
        {
            var validator = new LowerThanValidator<Person, int>(p => p.Age);

            var person = new Person { Age = 18 };
            Assert.That(validator.Validate(person, 18), Is.False);
        }
        public void Should_be_valid_when_length_is_between_values_using_instance_property()
        {
            var validator = new LengthValidator<Person>(p => p.Name.Length, p => p.Age);

            var person = new Person {Name = "Bob", Age = 8};
            Assert.That(validator.Validate(person, "ABCDE"), Is.True);
        }
        public void Can_add_negated_validator_rule_for_property()
        {
            SetupValidation.For<Person>(rules => rules.Property(p => p.Name).Not.Empty());
            var person = new Person { Name = "" };

            var rule = context.GetRuleSetsForType<Person>()[0].Rules.First() as ValidatorRule<Person, string>;
            Assert.That(rule.Validate(person).IsValid, Is.False);
        }
        public void Should_be_valid_when_inner_validator_is_invalid()
        {
            var validator = CreateMock<IValidator<Person, string>>();
            var negated = new NegatedValidator<Person, string>(validator);
            var person = new Person();

            validator.Expect(v => v.Validate(person, "Test")).Return(false);

            Assert.That(negated.Validate(person, "Test"), Is.True);
        }
Example #10
0
        public void Can_access_broken_rule_details()
        {
            var rule = CreateStub<IRule>();
            var person = new Person();
            var brokenRule = new BrokenRule(rule, person, "FullName", "Full Name", -123);

            Assert.That(brokenRule.InvalidInstance, Is.EqualTo(person));
            Assert.That(brokenRule.InvalidValue, Is.EqualTo(-123));
            Assert.That(brokenRule.PropertyDisplayName, Is.EqualTo("Full Name"));
            Assert.That(brokenRule.PropertyKey, Is.EqualTo("FullName"));
        }
Example #11
0
        public void Should_validate_against_validator()
        {
            var validator = CreateMock<IValidator<Person, string>>();
            var person = new Person {Name = "Bob"};
            var rule = new ValidatorRule<Person, string>("", "", validator, p => p.Name);

            validator.Expect(v => v.Validate(person, "Bob")).Return(true);

            rule.Validate(person);

            VerifyAll();
        }
Example #12
0
        public void Should_return_valid_result_if_validator_returned_valid()
        {
            var validator = CreateMock<IValidator<Person, string>>();
            var person = new Person { Name = "Bob" };
            var rule = new ValidatorRule<Person, string>("", "", validator, p => p.Name);

            validator.Stub(v => v.Validate(person, "Bob")).Return(true);

            var result = rule.Validate(person);

            Assert.That(result.IsValid, Is.True);
        }
Example #13
0
        public void Should_format_message()
        {
            var rule = CreateStub<IRule>();
            rule.Stub(r => r.Message).Return("{Instance.Name} has invalid {Property}: {Value}");

            var person = new Person {Name = "John Doe"};
            var brokenRule = new BrokenRule(rule, person, "Age", "Age", -123);

            var message = brokenRule.Message;

            Assert.That(message, Is.EqualTo("John Doe has invalid Age: -123"));
        }
        public void Should_always_be_valid_if_condition_is_not_met()
        {
            var person = new Person();

            var rule1 = new TestConditionalRule<Person>(true) { Condition = (p => false) };
            var rule2 = new TestConditionalRule<Person>(false) { Condition = (p => false) };

            var result1 = rule1.Validate(person);
            var result2 = rule2.Validate(person);

            Assert.That(result1.IsValid, Is.True);
            Assert.That(result2.IsValid, Is.True);
        }
        public void Should_run_validation_when_condition_is_not_set()
        {
            var person = new Person();

            var rule1 = new TestConditionalRule<Person>(true);
            var rule2 = new TestConditionalRule<Person>(false);

            var result1 = rule1.Validate(person);
            var result2 = rule2.Validate(person);

            Assert.That(result1.IsValid, Is.True);
            Assert.That(result2.IsValid, Is.False);
        }
Example #16
0
        public void Should_return_invalid_result_with_broken_rule_if_validator_returned_invalid()
        {
            var validator = CreateMock<IValidator<Person, string>>();
            var person = new Person { Name = "Bob" };
            var rule = new ValidatorRule<Person, string>("", "", validator, p => p.Name) { Message = "Invalid name" };

            validator.Stub(v => v.Validate(person, "Bob")).Return(false);

            var result = rule.Validate(person);

            Assert.That(result.IsValid, Is.False);
            Assert.That(result.BrokenRules[0].Message, Is.EqualTo("Invalid name"));
        }
Example #17
0
        public void Can_use_resource_as_message()
        {
            ValidationContext.ResourceManagers.Add(TestMessages.ResourceManager);

            var rule = CreateStub<IRule>();
            rule.Stub(r => r.Resource).Return("personInvalidName");

            var person = new Person();
            var brokenRule = new BrokenRule(rule, person, "Name", "Name", "John Doe");

            var message = brokenRule.Message;

            Assert.That(message, Is.EqualTo("John Doe is not a valid name."));
        }
Example #18
0
        public void Can_validate_against_current_validation_context()
        {
            var person = new Person();
            var expectedResult = new ValidationResult();

            var context = CreateMock<IValidationContext>();
            ValidationContext.Current = context;

            context.Expect(c => c.Validate(person)).Return(expectedResult);

            var result = Validate.Instance(person);

            Assert.That(result, Is.SameAs(expectedResult));

            VerifyAll();
        }
Example #19
0
        public void Can_validate_against_named_validation_context_using_alternate_syntax()
        {
            var person = new Person();
            var expectedResult = new ValidationResult();

            var context = CreateMock<IValidationContext>();
            ValidationContext.SetNamedContext("TestContext", context);

            context.Expect(c => c.Validate(person)).Return(expectedResult);

            var result = person.ValidateInContext("TestContext");

            Assert.That(result, Is.SameAs(expectedResult));

            VerifyAll();
        }
Example #20
0
        public void Should_return_all_broken_rules()
        {
            var person = new Person { Possessions = new List<Item> { new Item(), new Item() } };

            var rule = new ForEachRule<Person, Item>(p => p.Possessions);
            rule.Rules.Add(CreateMock<RuleBase<Item>>());
            rule.Rules.Add(CreateMock<RuleBase<Item>>());

            rule.Rules[0].Expect(r => r.Validate(person.Possessions[0])).Return(new RuleExecutionResult(new List<BrokenRule> { new BrokenRule(null, null, "", "", null) }));
            rule.Rules[1].Expect(r => r.Validate(person.Possessions[0])).Return(new RuleExecutionResult(new List<BrokenRule> { new BrokenRule(null, null, "", "", null), new BrokenRule(null, null, "", "", null) }));

            rule.Rules[0].Expect(r => r.Validate(person.Possessions[1])).Return(new RuleExecutionResult(new List<BrokenRule> { new BrokenRule(null, null, "", "", null), new BrokenRule(null, null, "", "", null) }));
            rule.Rules[1].Expect(r => r.Validate(person.Possessions[1])).Return(new RuleExecutionResult(new List<BrokenRule> { new BrokenRule(null, null, "", "", null) }) { StopEvaluation = true });

            var result = rule.Validate(person);

            Assert.That(result.IsValid, Is.False);
            Assert.That(result.StopEvaluation, Is.True);
            Assert.That(result.BrokenRules.Count, Is.EqualTo(6));
        }
Example #21
0
        public void Should_aggregate_results()
        {
            var person = new Person();

            var rules = new List<IRule>
                        {
                            CreateMock<IRule>(),
                            CreateMock<IRule>()
                        };

            rules[0].Stub(r => r.Validate(person)).Return(new RuleExecutionResult(new List<BrokenRule> { new BrokenRule(null, null, "", "", null), new BrokenRule(null, null, "", "", null) }));
            rules[1].Stub(r => r.Validate(person)).Return(new RuleExecutionResult(new List<BrokenRule> { new BrokenRule(null, null, "", "", null) }) { StopEvaluation = true });

            var ruleSet = new RuleSet(typeof(Person), rules);

            var result = ruleSet.Validate(person);

            Assert.That(result.IsValid, Is.False);
            Assert.That(result.BrokenRules.Count, Is.EqualTo(3));
        }
Example #22
0
        public void Can_stop()
        {
            var person = new Person();

            var rules = new List<IRule>
                        {
                            CreateMock<IRule>(),
                            CreateMock<IRule>(),
                            CreateMock<IRule>()
                        };

            rules[0].Stub(r => r.Validate(person)).Return(new RuleExecutionResult());
            rules[1].Stub(r => r.Validate(person)).Return(new RuleExecutionResult {StopEvaluation = true});
            rules[2].Expect(r => r.Validate(person)).Repeat.Never();

            var ruleSet = new RuleSet(typeof(Person), rules);

            ruleSet.Validate(person);

            VerifyAll();
        }
Example #23
0
        public void Should_validate_against_each_rule_if_not_stopped()
        {
            var person = new Person();

            var rules = new List<IRule>
                        {
                            CreateMock<IRule>(),
                            CreateMock<IRule>(),
                            CreateMock<IRule>()
                        };

            rules[0].Expect(r => r.Validate(person)).Return(new RuleExecutionResult());
            rules[1].Expect(r => r.Validate(person)).Return(new RuleExecutionResult());
            rules[2].Expect(r => r.Validate(person)).Return(new RuleExecutionResult());

            var ruleSet = new RuleSet(typeof (Person), rules);

            ruleSet.Validate(person);

            VerifyAll();
        }
Example #24
0
        public void Can_stop()
        {
            var person = new Person { Possessions = new List<Item> { new Item(), new Item(), new Item() } };

            var rule = new ForEachRule<Person, Item>(p => p.Possessions);
            rule.Rules.Add(CreateMock<RuleBase<Item>>());
            rule.Rules.Add(CreateMock<RuleBase<Item>>());

            rule.Rules[0].Expect(r => r.Validate(person.Possessions[0])).Return(new RuleExecutionResult());
            rule.Rules[1].Expect(r => r.Validate(person.Possessions[0])).Return(new RuleExecutionResult());

            rule.Rules[0].Expect(r => r.Validate(person.Possessions[1])).Return(new RuleExecutionResult {StopEvaluation = true});
            rule.Rules[1].Expect(r => r.Validate(person.Possessions[1])).Repeat.Never();

            rule.Rules[0].Expect(r => r.Validate(person.Possessions[2])).Repeat.Never();
            rule.Rules[1].Expect(r => r.Validate(person.Possessions[2])).Repeat.Never();

            rule.Validate(person);

            VerifyAll();
        }
Example #25
0
        public void Should_validate_each_rule_against_each_object_in_list()
        {
            var person = new Person {Possessions = new List<Item>{new Item(), new Item(), new Item()}};

            var rule = new ForEachRule<Person, Item>(p => p.Possessions);
            rule.Rules.Add(CreateMock<RuleBase<Item>>());
            rule.Rules.Add(CreateMock<RuleBase<Item>>());

            rule.Rules[0].Expect(r => r.Validate(person.Possessions[0])).Return(new RuleExecutionResult());
            rule.Rules[1].Expect(r => r.Validate(person.Possessions[0])).Return(new RuleExecutionResult());

            rule.Rules[0].Expect(r => r.Validate(person.Possessions[1])).Return(new RuleExecutionResult());
            rule.Rules[1].Expect(r => r.Validate(person.Possessions[1])).Return(new RuleExecutionResult());

            rule.Rules[0].Expect(r => r.Validate(person.Possessions[2])).Return(new RuleExecutionResult());
            rule.Rules[1].Expect(r => r.Validate(person.Possessions[2])).Return(new RuleExecutionResult());

            rule.Validate(person);

            VerifyAll();
        }
        public void Can_chain_validators()
        {
            SetupValidation.For<Person>(rules =>
                rules.Property(p => p.Name)
                    .Length(1, 10)
                    .Matches("^[A-Z][a-z]+$")
            );

            var person = new Person {Name = "JOhn"};

            var r1 = context.GetRuleSetsForType<Person>()[0].Rules.ElementAt(0) as ValidatorRule<Person, string>;
            var r2 = context.GetRuleSetsForType<Person>()[0].Rules.ElementAt(1) as ValidatorRule<Person, string>;

            Assert.That(r1.Validate(person).IsValid, Is.True);
            Assert.That(r2.Validate(person).IsValid, Is.False);
        }
Example #27
0
        public void Can_configure_and_validate_using_fluent_syntax()
        {
            SetupValidation.For<Person>(
                rules => {

                    rules.Not.Null();

                    rules.Property(p => p.Name)
                        .WithKey("_name")
                        .WithName("The person's name")
                        .Not.Empty().WithMessage("Name is required.")
                        .Length(2, 50).WithMessage("Name should be between 2 and 50 characters.")
                        .Matches("^([A-Z][a-z]* ?)+$");

                    rules.Property(p => p.Age)
                        .GreaterOrEqualTo(13).WithMessage("Age must be greater than 13")
                        .Convert(x => x.ToString())
                        .Length(1, 2).WithMessage("Age must be one or two characters");

                    rules.Property(p => p.Notes)
                        .Custom(notes => notes.Count <= 10).When(p => p.Age <= 6);

                    rules.ForEach(p => p.Notes)
                        .Not.Empty()
                        .Length(1, 255);

                    rules.Property(p => p.Possessions)
                        .Custom(possessions => possessions.Sum(i => i.Weight) <= 50).WithMessage("Total weights of possessions must be under 50 pounds.");

                    rules.ForEach(p => p.Possessions)
                        .Property(i => i.Weight)
                        .LowerThan(10).WithMessage("Can't carry a single item that weights more than 10 pounds.");

                });

            var p1 = new Person
                         {
                             Age = 21,
                             Name = "John Doe",
                             Notes = new List<string> { "Note 1" },
                             Possessions = new List<Item> { new Item { Weight = 5 } }
                         };

            var p2 = new Person
                         {
                             Age = 21,
                             Name = "John doe", // <-- should be invalid
                             Notes = new List<string> { "Note 1" },
                             Possessions = new List<Item> { new Item { Weight = 12 } } // <-- should be invalid
                         };

            var r1 = Validate.Instance(p1);
            var r2 = p2.Validate();

            Assert.That(r1.IsValid, Is.True);
            Assert.That(r2.IsValid, Is.False);
            Assert.That(r2.BrokenRules.Count, Is.EqualTo(2));

            Assert.That(r2.BrokenRules[0].PropertyKey, Is.EqualTo("_name"));
            Assert.That(r2.BrokenRules[0].Message, Is.EqualTo("The person's name does not have the correct format."));
        }