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 ClientsideMessageTester() { System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us"); System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us"); validator = new InlineValidator<TestModel>(); controllerContext = CreateControllerContext(); }
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 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 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 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 Expected_error_code_check() { bool exceptionCaught = false; try { var validator = new InlineValidator <Person> { v => v.RuleFor(x => x.Surname).NotNull().WithErrorCode("bar") }; validator.ShouldHaveValidationErrorFor(x => x.Surname, null as string).WithErrorCode("foo"); } catch (ValidationTestException e) { exceptionCaught = true; e.Message.ShouldEqual("Expected an error code of 'foo'. Actual error code was 'bar'"); } exceptionCaught.ShouldBeTrue(); }
public void Expected_severity_check() { bool exceptionCaught = false; try { var validator = new InlineValidator <Person> { v => v.RuleFor(x => x.Surname).NotNull().WithSeverity(Severity.Warning) }; validator.ShouldHaveValidationErrorFor(x => x.Surname, null as string).WithSeverity(Severity.Error); } catch (ValidationTestException e) { exceptionCaught = true; e.Message.ShouldEqual($"Expected a severity of '{nameof(Severity.Error)}'. Actual severity was '{nameof(Severity.Warning)}'"); } exceptionCaught.ShouldBeTrue(); }
// --- protected override FluentValidation.Results.ValidationResult ValidateFields() { var v = new InlineValidator <ChangePasswordModel>() { CascadeMode = CascadeMode.StopOnFirstFailure }; v.RuleFor(_ => _.New) .Must(Common.ValidationRules.BeValidPasswordLength).WithMessage("Invalid length") ; v.RuleFor(_ => _.TfaCode) .Must(Common.ValidationRules.BeValidTfaCode).WithMessage("Invalid format") .When(_ => !string.IsNullOrWhiteSpace(_.TfaCode)) ; return(v.Validate(this)); }
// --- protected override FluentValidation.Results.ValidationResult ValidateFields() { var v = new InlineValidator <ConfirmModel>() { CascadeMode = CascadeMode.StopOnFirstFailure }; v.RuleFor(_ => _.Email) .EmailAddress().WithMessage("Invalid format") .Must(Common.ValidationRules.BeValidEmailLength) ; v.RuleFor(_ => _.Captcha) .Must(Common.ValidationRules.BeValidCaptchaLength).WithMessage("Invalid length") ; return(v.Validate(this)); }
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); }
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 Vai_retornar_caminhao_nao_cadastrado() { var caminhao = new Caminhao() { Id = 1 }; var validator = new InlineValidator <Caminhao>(); caminhaoRepository.Setup(c => c.IdExistente(It.IsAny <long>())) .ReturnsAsync(false); validarCaminhaoCadastrado.AdicionarValidacao(validator); var resultado = validator.Validate(caminhao); Assert.IsFalse(resultado.IsValid); ContemErro(resultado, CodigoDoErroValidarCaminhaoCadastrado01); }
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 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"); }
public void Includes_all_rulesets() { var validator = new InlineValidator <Person>(); validator.RuleFor(x => x.Forename).NotNull(); validator.RuleSet("Test1", () => { validator.RuleFor(x => x.Surname).NotNull(); }); validator.RuleSet("Test2", () => { validator.RuleFor(x => x.Age).GreaterThan(0); }); var result = validator.Validate(new Person(), options => { options.IncludeAllRuleSets(); }); result.Errors.Count.ShouldEqual(3); }
public async Task Includes_all_rulesets_async() { var validator = new InlineValidator <Person>(); validator.RuleFor(x => x.Forename).MustAsync((x, t) => Task.FromResult(x != null)); validator.RuleSet("Test1", () => { validator.RuleFor(x => x.Surname).MustAsync((x, t) => Task.FromResult(x != null)); }); validator.RuleSet("Test2", () => { validator.RuleFor(x => x.Age).MustAsync((x, t) => Task.FromResult(x > 0)); }); var result = await validator.ValidateAsync(new Person(), options => { options.IncludeAllRuleSets(); }); result.Errors.Count.ShouldEqual(3); }
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}""}}"); }
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}""}}"); }
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}""}}"); }
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}""}}"); }
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""}}"); }
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 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); }
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"); }
public void Customm_within_ruleset() { var validator = new InlineValidator <Person>(); validator.RuleSet("foo", () => { validator.Custom(x => { return(new ValidationFailure("x", "y")); }); }); validator.RuleSet("bar", () => { validator.Custom(x => { return(new ValidationFailure("x", "y")); }); }); var result = validator.Validate(new Person(), ruleSet: "foo"); result.Errors.Count.ShouldEqual(1); }
public void Unexpected_state_check() { bool exceptionCaught = false; try { var validator = new InlineValidator <Person> { v => v.RuleFor(x => x.Surname).NotNull().WithState(x => "bar"), v => v.RuleFor(x => x.Surname).NotNull().WithState(x => "foo"), }; validator.ShouldHaveValidationErrorFor(x => x.Surname, null as string).WithoutCustomState("bar"); } catch (ValidationTestException e) { exceptionCaught = true; e.Message.ShouldEqual("Found an unexpected custom state of 'bar'"); } exceptionCaught.ShouldBeTrue(); }
public async Task Combines_rulesets_and_explicit_properties_async() { var validator = new InlineValidator <Person>(); validator.RuleFor(x => x.Forename).NotNull(); validator.RuleFor(x => x.Surname).NotNull(); validator.RuleSet("Test", () => { validator.RuleFor(x => x.Age).GreaterThan(0); }); var result = await validator.ValidateAsync(new Person(), options => { options.IncludeRuleSets("Test"); options.IncludeProperties(x => x.Forename); }); result.Errors.Count.ShouldEqual(2); result.Errors[0].PropertyName.ShouldEqual("Forename"); result.Errors[1].PropertyName.ShouldEqual("Age"); }
public void Matches_any_failure() { var validator = new InlineValidator <Person> { v => v.RuleFor(x => x.Surname).NotEqual("foo"), }; var resultWithFailure = validator.TestValidate(new Person { Surname = "foo" }); var resultWithoutFailure = validator.TestValidate(new Person { Surname = "" }); Assert.Throws <ValidationTestException>(() => resultWithoutFailure.ShouldHaveAnyValidationError()); Assert.Throws <ValidationTestException>(() => resultWithFailure.ShouldNotHaveAnyValidationErrors()); // Neither should throw. resultWithFailure.ShouldHaveAnyValidationError(); resultWithoutFailure.ShouldNotHaveAnyValidationErrors(); }
public void Uses_useful_error_message_when_used_on_non_property() { var validator = new InlineValidator <Person>(); validator.RuleForEach(x => x.NickNames.AsEnumerable()).NotNull(); bool thrown = false; try { validator.Validate(new Person { NickNames = new string[] { null, null } }); } catch (System.InvalidOperationException ex) { thrown = true; ex.Message.ShouldEqual("Could not infer property name for expression: x => x.NickNames.AsEnumerable(). Please explicitly specify a property name by calling OverridePropertyName as part of the rule chain. Eg: RuleForEach(x => x).NotNull().OverridePropertyName(\"MyProperty\")"); } thrown.ShouldBeTrue(); }
public void New_CustomAsync_within_ruleset() { var validator = new InlineValidator <Person>(); validator.RuleSet("foo", () => { validator.RuleFor(x => x).CustomAsync(async(x, ctx, cancel) => { ctx.AddFailure("x", "y"); }); }); validator.RuleSet("bar", () => { validator.RuleFor(x => x).CustomAsync(async(x, ctx, cancel) => { ctx.AddFailure("x", "y"); }); }); var result = validator.ValidateAsync(new Person(), ruleSet: "foo").Result; result.Errors.Count.ShouldEqual(1); }
public void For_IsNull_When_PropertyValueIsNull_Then_ValidationErrorIsNotReturned() { // Arrange: var validator = new InlineValidator <Person>(); validator.Setup(x => x.Name) .IsNull(); var toValidate = new Person { Name = null, Age = default }; // Act: var validationErrors = validator.Validate(toValidate); // Assert: validationErrors.Count.Should().Be(0); }
public void When_runs_outside_RuleForEach_loop() { // Shouldn't throw an exception if the condition is run outside the loop. var validator = new InlineValidator <Tuple <Person> >(); validator.RuleForEach(x => x.Item1.Orders).Must(x => false) .When(x => x.Item1 != null); var result = validator.Validate(Tuple.Create((Person)null)); result.IsValid.ShouldBeTrue(); result = validator.Validate(Tuple.Create(new Person() { Orders = new List <Order> { new Order() } })); result.IsValid.ShouldBeFalse(); }
public async Task Transforms_collection_element_with_propagated_original_object_async() { var validator = new InlineValidator <Person>(); validator.TransformForEach(x => x.Children, (parent, children) => new { ParentName = parent.Surname, Children = children }) .Must(context => context.ParentName == context.Children.Surname); var child = new Person { Surname = "Pupa" }; var result = await validator.ValidateAsync(new Person() { Surname = "Lupa", Children = new List <Person> { child } }); result.IsValid.ShouldBeFalse(); result.Errors.Count.ShouldEqual(1); }
public void New_Custom_within_ruleset() { var validator = new InlineValidator <Person>(); validator.RuleSet("foo", () => { validator.RuleFor(x => x).Custom((x, ctx) => { ctx.AddFailure("x", "y"); }); }); validator.RuleSet("bar", () => { validator.RuleFor(x => x).Custom((x, ctx) => { ctx.AddFailure("x", "y"); }); }); var result = validator.Validate(new Person(), v => v.IncludeRuleSets("foo")); result.Errors.Count.ShouldEqual(1); }
public void Expected_state_check() { bool exceptionCaught = false; try { var validator = new InlineValidator <Person> { v => v.RuleFor(x => x.Surname).NotNull().WithState(x => "bar") }; validator.TestValidate(new Person()) .ShouldHaveValidationErrorFor(x => x.Surname) .WithCustomState("foo"); } catch (ValidationTestException e) { exceptionCaught = true; e.Message.ShouldEqual("Expected custom state of 'foo'. Actual state was 'bar'"); } exceptionCaught.ShouldBeTrue(); }
public void Setup() { System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us"); validator = new InlineValidator<TestModel>(); controllerContext = CreateControllerContext(); }
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_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 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(); }