public void Validates_with_nullable_property() {
			var validator = new TestValidator(v => v.RuleFor(x => x.Id).LessThanOrEqualTo(x => x.NullableInt));

			var resultNull = validator.Validate(new Person { Id = 0, NullableInt = null });
			var resultLess = validator.Validate(new Person { Id = 0, NullableInt = -1 });
			var resultEqual = validator.Validate(new Person { Id = 0, NullableInt = 0 });
			var resultMore = validator.Validate(new Person { Id = 0, NullableInt = 1 });

			resultNull.IsValid.ShouldBeFalse();
			resultLess.IsValid.ShouldBeFalse();
			resultEqual.IsValid.ShouldBeTrue();
			resultMore.IsValid.ShouldBeTrue();
		}
        public void When_exact_length_rule_failes_error_should_have_exact_length_error_errorcode()
        {
            var validator = new TestValidator { v => v.RuleFor(x => x.Surname).Length(2) };

            var result = validator.Validate(new Person() { Surname = "test" });
            var error = result.Errors.SingleOrDefault(e => e.ErrorCode == "exact_length_error");

            error.ShouldNotBeNull();
            error.PropertyName.ShouldEqual("Surname");
            error.AttemptedValue.ShouldEqual("test");
            error.FormattedMessageArguments.Length.ShouldEqual(0);

            error.FormattedMessagePlaceholderValues.Count.ShouldEqual(5);
            error.FormattedMessagePlaceholderValues.ContainsKey("PropertyName").ShouldBeTrue();
            error.FormattedMessagePlaceholderValues.ContainsKey("PropertyValue").ShouldBeTrue();
            error.FormattedMessagePlaceholderValues.ContainsKey("MinLength").ShouldBeTrue();
            error.FormattedMessagePlaceholderValues.ContainsKey("MaxLength").ShouldBeTrue();
            error.FormattedMessagePlaceholderValues.ContainsKey("TotalLength").ShouldBeTrue();

            error.FormattedMessagePlaceholderValues["PropertyName"].ShouldEqual("Surname");
            error.FormattedMessagePlaceholderValues["PropertyValue"].ShouldEqual("test");
            error.FormattedMessagePlaceholderValues["MinLength"].ShouldEqual(2);
            error.FormattedMessagePlaceholderValues["MaxLength"].ShouldEqual(2);
            error.FormattedMessagePlaceholderValues["TotalLength"].ShouldEqual(4);
        }
Ejemplo n.º 3
0
        public void Should_succeed_on_case_insensitive_comparison()
        {
            var validator = new TestValidator { v => v.RuleFor(x => x.Surname).Equal("FOO", StringComparer.OrdinalIgnoreCase) };
            var result = validator.Validate(new Person { Surname = "foo" });

            result.IsValid.ShouldBeTrue();
        }
 public void Sets_localised_message_via_expression()
 {
     var validator = new TestValidator();
     validator.RuleFor(x => x.Surname).NotEmpty().WithLocalizedMessage(() => MyResources.notempty_error);
     var result = validator.Validate(new Person());
     result.Errors.Single().ErrorMessage.ShouldEqual("foo");
 }
Ejemplo n.º 5
0
		public void When_there_is_a_value_then_the_validator_should_pass() {
			var validator = new TestValidator {
				v => v.RuleFor(x => x.Surname).NotEmpty()
			};

			var result = validator.Validate(new Person { Surname = "Foo" });
			result.IsValid.ShouldBeTrue();
		}
Ejemplo n.º 6
0
		public void When_value_is_Default_for_type_validator_should_fail_datetime() {
			var validator = new TestValidator {
				v => v.RuleFor(x => x.DateOfBirth).NotEmpty()
			};

			var result = validator.Validate(new Person { DateOfBirth = default(DateTime) });
			result.IsValid.ShouldBeFalse();
		}
Ejemplo n.º 7
0
		public void When_value_is_empty_string_validator_should_pass() {
			var validator = new TestValidator {
				v => v.RuleFor(x => x.Surname).Empty()
			};

			var result = validator.Validate(new Person { Surname = "" });
			result.IsValid.ShouldBeTrue();
		}
		public void Uses_localized_name() {
			var validator = new TestValidator {
				v => v.RuleFor(x => x.Surname).NotNull().WithLocalizedName(() => MyResources.CustomProperty)
			};

			var result = validator.Validate(new Person());
			result.Errors.Single().ErrorMessage.ShouldEqual("'foo' must not be empty.");
		}
		public void When_passing_string_to_localizable_lambda_should_convert_to_string_accessor() {
			var validator = new TestValidator() {
				v => v.RuleFor(x => x.Surname).SetValidator(new FooValidator())
			};

			var result = validator.Validate(new Person());
			result.Errors.Single().ErrorMessage.ShouldEqual("foo");
		}
        public void Can_access_expression_in_message()
        {
            var v = new TestValidator();
            v.RuleFor(x => x.Forename).Matches(@"^\w\d$").WithMessage("test {RegularExpression}");

            var result = v.Validate(new Person {Forename = ""});
            result.Errors.Single().ErrorMessage.ShouldEqual(@"test ^\w\d$");
        }
Ejemplo n.º 11
0
		public void When_value_is_whitespace_validation_should_fail() {
			var validator = new TestValidator {
				v => v.RuleFor(x => x.Surname).NotEmpty()
			};

			var result = validator.Validate(new Person { Surname = "         " });
			result.IsValid.ShouldBeFalse();
		}
		public void Validates_across_properties() {
			var validator = new TestValidator(
				v => v.RuleFor(x => x.Forename).NotEqual(x => x.Surname)
			);

			var result = validator.Validate(new Person { Surname = "foo", Forename = "foo" });
			result.IsValid.ShouldBeFalse();
		}
Ejemplo n.º 13
0
        public void Fails_when_collection_empty()
        {
            var validator = new TestValidator {
                v => v.RuleFor(x => x.Children).NotEmpty()
            };

            var result = validator.Validate(new Person { Children = new List<Person>() });
            result.IsValid.ShouldBeFalse();
        }
Ejemplo n.º 14
0
        public void When_validation_fails_error_should_be_set()
        {
            var validator = new TestValidator {
                v => v.RuleFor(x => x.Surname).NotEmpty()
            };

            var result = validator.Validate(new Person { Surname = null });
            result.Errors.Single().ErrorMessage.ShouldEqual("'Surname' should not be empty.");
        }
        public void Can_use_placeholders_with_localized_messages_using_expressions()
        {
            var validator = new TestValidator {
                v => v.RuleFor(x => x.Surname).NotNull().WithLocalizedMessage(() => TestMessages.PlaceholderMessage, x => 1)
            };

            var result = validator.Validate(new Person());
            result.Errors.Single().ErrorMessage.ShouldEqual("Test 1");
        }
		public void Resolves_nested_properties() {
			var validator = new TestValidator {
				v => v.RuleFor(x => x.Address.Country).NotNull()
			};

			var error = validator.Validate(new Person { Address = new Address() }).Errors.Single();
			error.PropertyName.ShouldEqual("Address.Country");

		}
        public void When_input_is_null_then_the_validator_should_pass()
        {
            var validator = new TestValidator {
                v => v.RuleFor(x => x.Surname).Length(5)
            };

            var result = validator.Validate(new Person {Surname = null});
            result.IsValid.ShouldBeTrue();
        }
        public void Custom_property_validators_should_respect_ResourceProvider()
        {
            ValidatorOptions.ResourceProviderType = typeof(MyResources);
            var validator = new TestValidator {
                v => v.RuleFor(x => x.Surname).SetValidator(new MyPropertyValidator())
            };

            var results = validator.Validate(new Person());
            results.Errors.Single().ErrorMessage.ShouldEqual("foo");
        }
		public void ResourceProviderType_overrides_default_messagesnote() {
			ValidatorOptions.ResourceProviderType = typeof(MyResources);

			var validator = new TestValidator() {
				v => v.RuleFor(x => x.Surname).NotEmpty()
			};

			var result = validator.Validate(new Person());
			result.Errors.Single().ErrorMessage.ShouldEqual("foo");
		}
		public void Overwrites_resoruce_type_when_using_custom_ResourceProvider_and_custom_ResourceAccessorProvider() {
			ValidatorOptions.ResourceProviderType = typeof(OverrideResources);

			var validator = new TestValidator {
				v => v.RuleFor(x => x.Surname).NotNull().WithLocalizedName(() => MyResources.CustomProperty, new FallbackAwareResourceAccessorBuilder())
			};

			var result = validator.Validate(new Person());
			result.Errors.Single().ErrorMessage.ShouldEqual("'bar' must not be empty.");
		}
		public void Does_not_overwrite_resource_when_using_custom_ResourceProvider() {
			ValidatorOptions.ResourceProviderType = typeof(OverrideResources);
			
			var validator = new TestValidator {
				v => v.RuleFor(x => x.Surname).NotNull().WithLocalizedName(() => MyResources.CustomProperty)
			};

			var result = validator.Validate(new Person());
			result.Errors.Single().ErrorMessage.ShouldEqual("'foo' must not be empty.");
		}
		public void Uses_custom_property_name() {
			ValidatorOptions.PropertyNameResolver = (type, prop, expr) => "foo";

			var validator = new TestValidator() {
				v => v.RuleFor(x => x.Surname).NotNull()
			};

			var error = validator.Validate(new Person()).Errors.Single();
			error.PropertyName.ShouldEqual("foo");
		}
		public void Invokes_dependent_rule_if_parent_rule_passes() {
			var validator = new TestValidator();
			validator.RuleFor(x => x.Surname).NotNull()
				.DependentRules(d => {
					d.RuleFor(x => x.Forename).NotNull();
				});

			var results = validator.Validate(new Person {Surname = "foo"});
			results.Errors.Count.ShouldEqual(1);
			results.Errors.Single().PropertyName.ShouldEqual("Forename");
		}
        public void Scale_and_precision_should_work()
        {
            var validator = new TestValidator(v => v.RuleFor(x => x.Discount).SetValidator(new ScalePrecisionValidator(2, 4)));

            var result = validator.Validate(new Person {Discount = 123.456778m});
            Assert.False(result.IsValid);

            result = validator.Validate(new Person {Discount = 12.34M});
            Assert.True(result.IsValid);

            result = validator.Validate(new Person {Discount = 12.3414M});
            result.IsValid.ShouldBeFalse();

            result = validator.Validate(new Person {Discount = 1.344M});
            result.IsValid.ShouldBeFalse();

            result = validator.Validate(new Person {Discount = 156.3M});
            result.IsValid.ShouldBeTrue();

            result = validator.Validate(new Person {Discount = 1565.0M}); // fail as it counts zeros
            result.IsValid.ShouldBeFalse();

            validator = new TestValidator(v => 
                v.RuleFor(x => x.Discount)
                    .SetValidator(new ScalePrecisionValidator(2, 4) {IgnoreTrailingZeros = true}));

            result = validator.Validate(new Person {Discount = 1565.0M}); // ignores zeros now
            result.IsValid.ShouldBeTrue();

            result = validator.Validate(new Person {Discount = 15655.0M});
            result.IsValid.ShouldBeFalse();

            result = validator.Validate(new Person {Discount = 155.0000000000000000000000000M});
            result.IsValid.ShouldBeTrue();

            result = validator.Validate(new Person {Discount = 155.0000000000000000000000001M});
            result.IsValid.ShouldBeFalse();

            result = validator.Validate(new Person {Discount = 00000000000000000000155.0000000000000000000000000M});
            result.IsValid.ShouldBeTrue();
        }
Ejemplo n.º 25
0
		public void Executes_rule_for_each_item_in_collection() {
			var validator = new TestValidator {
				v => v.RuleForEach(x => x.NickNames).NotNull()
			};

			var person = new Person {
				NickNames =  new[] { null, "foo", null }
			};

			var result = validator.Validate(person);
			result.Errors.Count.ShouldEqual(2);
		}
        public void WrapperSucceedsIfNotNullValueSucceedsForWrappedValidator()
        {
            var validator = new TestValidator();
            var wrapperValidator = new NullIgnoringValidatorWrapper(validator);
            object value = "test value";

            var rawResults = validator.Validate(value);
            var wrapperResults = wrapperValidator.Validate(value);

            Assert.IsTrue(rawResults.IsValid);
            Assert.IsTrue(wrapperResults.IsValid);
        }
Ejemplo n.º 27
0
        public void WrapperIgnoresNullValues()
        {
            var    validator        = new TestValidator();
            var    wrapperValidator = new NullIgnoringValidatorWrapper(validator);
            object value            = null;

            var rawResults     = validator.Validate(value);
            var wrapperResults = wrapperValidator.Validate(value);

            Assert.IsFalse(rawResults.IsValid);
            Assert.AreEqual("Invalid value", rawResults.ElementAt(0).Message);
            Assert.IsTrue(wrapperResults.IsValid);
        }
        public void WrapperIgnoresNullValues()
        {
            var validator = new TestValidator();
            var wrapperValidator = new NullIgnoringValidatorWrapper(validator);
            object value = null;

            var rawResults = validator.Validate(value);
            var wrapperResults = wrapperValidator.Validate(value);

            Assert.IsFalse(rawResults.IsValid);
            Assert.AreEqual("Invalid value", rawResults.ElementAt(0).Message);
            Assert.IsTrue(wrapperResults.IsValid);
        }
Ejemplo n.º 29
0
 public ResponseModel ValidateTestInsData(TestInsQueryFilter testInsQueryFilter)
 {
     try
     {
         TestValidator validator        = new TestValidator();
         var           validationResult = validator.Validate(testInsQueryFilter);
         return(MainValidator.IterationValidationResult(validationResult));
     }
     catch (Exception err)
     {
         throw new Exception(err.Message);
     }
 }
Ejemplo n.º 30
0
		public void Correctly_gets_collection_indicies() {
			var validator = new TestValidator {
				v => v.RuleForEach(x => x.NickNames).NotNull()
			};

			var person = new Person {
				NickNames = new[] { null, "foo", null }
			};

			var result = validator.Validate(person);
			result.Errors[0].PropertyName.ShouldEqual("NickNames[0]");
			result.Errors[1].PropertyName.ShouldEqual("NickNames[2]");
		}
        public void GivenValidDateTimeExtensionMethod_WhenDateTimeProvided_ThenShouldReturnExpectedResult(
            DateTime reservationDate, bool expectedResult)
        {
            var sut = new TestValidations
            {
                DateTime = reservationDate
            };

            var validator = new TestValidator();
            var result    = validator.Validate(sut);

            Assert.Equal(result.IsValid, expectedResult);
        }
        public void IsValid()
        {
            var entity = new TestEntity
            {
                Url      = "http://www.google.com/",
                HttpUrl  = "http://www.google.com/",
                HttpsUrl = "https://www.google.com/"
            };

            var validator = new TestValidator();
            var result    = validator.Validate(entity);

            Assert.IsTrue(result.IsValid);
        }
        public void WrapperFailsIfNotNullValueFailsForWrappedValidator()
        {
            var validator = new TestValidator();
            var wrapperValidator = new NullIgnoringValidatorWrapper(validator);
            object value = "some value";

            var rawResults = validator.Validate(value);
            var wrapperResults = wrapperValidator.Validate(value);

            Assert.IsFalse(rawResults.IsValid);
            Assert.AreEqual("Invalid value", rawResults.ElementAt(0).Message);
            Assert.IsFalse(wrapperResults.IsValid);
            Assert.AreEqual("Invalid value", wrapperResults.ElementAt(0).Message);
        }
		public void Dependent_rules_inside_ruleset() {
			var validator = new TestValidator();
			validator.RuleSet("MyRuleSet", () => {

				validator.RuleFor(x => x.Surname).NotNull()
					.DependentRules(d => {
						d.RuleFor(x => x.Forename).NotNull();
					});
			});

			var results = validator.Validate(new Person { Surname = "foo" }, ruleSet: "MyRuleSet");
			results.Errors.Count.ShouldEqual(1);
			results.Errors.Single().PropertyName.ShouldEqual("Forename");
		}
Ejemplo n.º 35
0
        public void WrapperFailsIfNotNullValueFailsForWrappedValidator()
        {
            var    validator        = new TestValidator();
            var    wrapperValidator = new NullIgnoringValidatorWrapper(validator);
            object value            = "some value";

            var rawResults     = validator.Validate(value);
            var wrapperResults = wrapperValidator.Validate(value);

            Assert.IsFalse(rawResults.IsValid);
            Assert.AreEqual("Invalid value", rawResults.ElementAt(0).Message);
            Assert.IsFalse(wrapperResults.IsValid);
            Assert.AreEqual("Invalid value", wrapperResults.ElementAt(0).Message);
        }
        public void Invalid()
        {
            var entity = new TestEntity
            {
                Url      = "ftp://www.google.com/",
                HttpUrl  = "https://www.google.com/",
                HttpsUrl = "http://www.google.com/"
            };

            var validator = new TestValidator();
            var result    = validator.Validate(entity);

            Assert.IsFalse(result.IsValid);
            Assert.AreEqual(3, result.Errors.Count);
        }
Ejemplo n.º 37
0
 public void should_be_valid_if_all_settings_valid()
 {
     _validator.Validate(_emailSettings).IsValid.Should().BeTrue();
 }
Ejemplo n.º 38
0
        public ActionResult App(Test account)
        {
            //validate my data

            TestValidator    validator = new TestValidator();
            ValidationResult result    = validator.Validate(account);
            int time;

            if (Session["time"] == null)
            {
                time            = 0;
                Session["time"] = time;
                return(View("App", account));
            }

            time = (int)Session["time"];

            Session["time"] = time + 1;


            if (result.IsValid == false)
            {
                if (time >= 3)
                {
                    // Show the captcha.
                    account.b          = true;
                    ViewBag.ErrMessage = "Invalid Captcha";
                    return(View("App", account));
                }

                else
                {
                    ViewBag.Err = "Invalid CouponCode";
                    return(View("App", account));
                }
            }

            else
            {
                return(View("Success", account));
            }


            /*     if (count <= 3)
             * {
             *   count=count +1;
             *
             *   ViewBag.error = "Invalid CouponCode";
             *   return View("Index", account);
             * }
             * else
             * {
             *
             *   return View("captcha",account);
             * }
             * }
             *
             * else
             * {
             * ViewBag.account = account;
             * return View("Success");
             * }
             * }
             *
             */
            /* public ActionResult Check(Account acc)
             *   {
             *
             *
             *       if (!this.IsCaptchaValid(""))
             *       {
             *           ViewBag.error = "Invalid Captcha";
             *           return View("captcha", acc);
             *       }
             *       else
             *       {
             *           ViewBag.account = acc;
             *           return View("Success");
             *
             *       }
             *   }*/
        }