public void isRegionNameInvalid_inValidRegionName_RegionIsNotCreated(string invalidName)
        {
            DateTime date = DateTime.Today;

            Region rOne = new Region()
            {
                regionName = invalidName,
                frequency  = 10,
                firstDate  = new DateTime(date.Year + 1, date.Month, date.Day)
            };

            List <ValidationResult> results = ClassValidator <Region> .Validate(rOne);

            Assert.Single(results);

            switch (rOne.regionName.Length)
            {
            case int n when n < 2:
                Assert.Equal("Region name must be at least 2 characters long", results[0].ToString());
                break;

            case int n when n > 40:
                Assert.Equal("Region name cannot exceed 40 characters in length", results[0].ToString());
                break;
            }
        }
Exemple #2
0
        public void WhenTagIsSpecified_MatchTagsContainOnlyMatchs()
        {
            // only property with 'typeof(Error)' as tag
            IClassValidator cv            = new ClassValidator(typeof(aEntity));
            var             invalidValues = cv.GetInvalidValues(new aEntity(), new[] { "information" }).ToArray();

            invalidValues.First(iv => iv.PropertyName == "ValueMin").MatchTags.Should().Have.SameValuesAs("information");

            invalidValues = cv.GetInvalidValues(new aEntity {
                ValueMinMax = 101
            }, new[] { "information", "warning" }).ToArray();
            invalidValues.First(iv => iv.PropertyName == "ValueMinMax").MatchTags.Should().Have.SameValuesAs("warning");
            invalidValues.First(iv => iv.PropertyName == "ValueMin").MatchTags.Should().Have.SameValuesAs("warning",
                                                                                                          "information");

            invalidValues = cv.GetInvalidValues(new aEntity(), new[] { "error", "warning" }).ToArray();
            invalidValues.First(iv => iv.PropertyName == "ValueMinMax").MatchTags.Should().Have.SameValuesAs("error");
            invalidValues.First(iv => iv.PropertyName == "ValueMin").MatchTags.Should().Have.SameValuesAs("warning");

            invalidValues = cv.GetInvalidValues(new aEntity {
                ValueMinMax = 120
            }, new[] { "error", "warning" }).ToArray();
            invalidValues.First(iv => iv.PropertyName == "ValueMinMax").MatchTags.Should().Have.SameValuesAs("error", "warning");
            invalidValues.First(iv => iv.PropertyName == "ValueMin").MatchTags.Should().Have.SameValuesAs("warning");

            invalidValues = cv.GetInvalidValues(new aEntity(), new[] { "error", null }).ToArray();
            invalidValues.First(iv => iv.PropertyName == "ValueMinMax").MatchTags.Should().Have.SameValuesAs("error");
            invalidValues.First(iv => iv.PropertyName == "ValueWithoutTags").MatchTags.Should().Have.Count.EqualTo(0);
        }
        public static IEnumerable <ValidationResult> Validate(this UpdateTokenModel requestData)
        {
            var validationResults = new List <ValidationResult>();

            validationResults.AddRange(ClassValidator <UpdateTokenModel> .Validate(requestData));
            validationResults.AddRange(ClassValidator <TransactionModel> .Validate(requestData.Transaction ?? new TransactionModel()));


            foreach (var service in requestData.Services ?? new List <ServiceModel>())
            {
                validationResults.AddRange(ClassValidator <ServiceModel> .Validate(service));
            }

            foreach (var allocation in requestData.Allocations ?? new List <AllocationModel>())
            {
                validationResults.AddRange(ClassValidator <AllocationModel> .Validate(allocation));
            }

            foreach (var traveler in requestData.Travelers ?? new List <TravelerModel>())
            {
                validationResults.AddRange(ClassValidator <TravelerModel> .Validate(traveler));
            }

            return(validationResults);
        }
Exemple #4
0
        public void CanBeSerialized()
        {
            TestsContext.AssumeSystemTypeIsSerializable();
            ClassValidator cv = new ClassValidator(typeof(Address));

            NHAssert.IsSerializable(cv);
        }
Exemple #5
0
        public void ProofFor_NHV48()
        {
            IClassValidator cv = new ClassValidator(typeof(Book));

            cv.GetInvalidValues(new Book(), BTags.Draft).Should().Have.Count.EqualTo(1);
            cv.GetInvalidValues(new Book(), BTags.Publish).Should().Have.Count.EqualTo(2);
        }
Exemple #6
0
        public void WhenTagsIncludeOnlyNull_ValidateOnlyWithNoTags()
        {
            // only property 'ValueWithoutTags'
            IClassValidator cv = new ClassValidator(typeof(Entity));

            cv.GetInvalidValues(new Entity(), new object[] { null }).Should().Have.Count.EqualTo(1);
        }
        public void Multiple_Errors_On_A_Property_Show_In_Validation_Error()
        {
            // arrange
            var profile = new DuplicateMappingProfile();

            var model = new Model1
            {
                Age  = 18,
                Name = "test"
            };

            _validator = new ClassValidator <Model1>(profile.MappingExpressions.OfType <IMappingExpression <Model1> >().Single(), _settings);


            // act
            var result = _validator.Validate(model);

            // assert
            result.Success.Should().BeFalse();

            result.Errors.Should().ContainKey("Name");
            var nameErrors = result.Errors["Name"];

            nameErrors.Count.Should().Be(2);
            nameErrors.Should().Contain(e => e == "Name must be at least 13");
            nameErrors.Should().Contain(e => e == "Name should not be longer than 3");
        }
Exemple #8
0
        public void WhenTagsIncludeNull_ValidateOnlyWithTagAndWithNoTags()
        {
            // only properties with 'typeof(Error)' as tag and with no tag (prop 'ValueWithoutTags')
            IClassValidator cv = new ClassValidator(typeof(Entity));

            cv.GetInvalidValues(new Entity(), typeof(Error), null).Should().Have.Count.EqualTo(2);
        }
Exemple #9
0
        public void WhenTagIsSpecified_ValidateOnlyWithTag()
        {
            // only property with 'typeof(Error)' as tag
            IClassValidator cv = new ClassValidator(typeof(Entity));

            cv.GetInvalidValues(new Entity(), typeof(Error)).Should().Have.Count.EqualTo(1);
        }
Exemple #10
0
        public void WhenNoTagIsSpecified_ValidateAnything()
        {
            // all propeties are wrong
            IClassValidator cv = new ClassValidator(typeof(Entity));

            cv.GetInvalidValues(new Entity()).Should().Have.Count.EqualTo(4);
        }
        public void IfTest_class()
        {
            List <Row> list = new List <Row>()
            {
                new Row()
                {
                    Key = "A", DecimalValue = "zz"
                },
                new Row()
                {
                    Key = "A", DecimalValue = "1"
                },                                           // error
                new Row()
                {
                    Key = "", DecimalValue = "1", DateTimeValue = null
                },                                                                // error
                new Row()
                {
                    Key = "", DecimalValue = "", DateTimeValue = "20012301"
                }                                                                     // error
            };

            ClassValidator <Row> validator = ClassValidator <Row>
                                             .Init(new ClassValidatorOption()
            {
                ShowRowIndex = true
            })
                                             .ForIf(x => x.DecimalValue, e => e.Key != "A", p => p.TryParseDecimal())
                                             .ForIf(x => x.DateTimeValue, e => string.IsNullOrEmpty(e.Key), p => p.IsNotNullOrEmpty())
                                             .ValidateList(list);

            Assert.Equal(2, validator.ValidationErrors.Count);
        }
Exemple #12
0
        [InlineData(false)] // A invalid format
        public void SetInactive_ValidValues_InactiveValueChanged(bool inactiveState)
        {
            subscriber.inactive = inactiveState;                            //Set the attribute to the string being passed in
            var errors = ClassValidator <Subscriber> .Validate(subscriber); //Set errors to the return value from the validator

            Assert.Empty(errors);                                           //make sure only a single error is returned
            ResetSubscriber();                                              //reset the subscriber
        }
        public void ShouldUseTheValidatorForTheProperty()
        {
            var cv = new ClassValidator(typeof(ObjWithPropertyValidator));
            var iv = cv.GetInvalidValues(new ObjWithPropertyValidator()).ToArray();

            iv.Should().Not.Be.Empty();
            iv.Single().Message.Should().Be.EqualTo("something for prop");
        }
Exemple #14
0
        private void GivingRulesFor(string propertyName, out ITagableRule minAttribute, out ITagableRule maxAttribute)
        {
            IClassValidator         cv = new ClassValidator(typeof(Entity));
            IEnumerable <Attribute> ma = cv.GetMemberConstraints(propertyName);

            minAttribute = (ITagableRule)ma.First(a => a.TypeId == minTypeId);
            maxAttribute = (ITagableRule)ma.First(a => a.TypeId == maxTypeId);
        }
Exemple #15
0
 public PostClassService(
     IDefaultDbContext context,
     ClassValidator entityValidator,
     PostClassSpecificationsValidator domainValidator
     ) : base(entityValidator, domainValidator)
 {
     Context = context;
 }
Exemple #16
0
        [InlineData(1)]//valid case
        public void isValidLocationID_ValidLocationID_NoErrorsReturned(int locationID)
        {
            subscriber.locationID = locationID;                             //Set the locationID to the int passed in
            var errors = ClassValidator <Subscriber> .Validate(subscriber); //Set errors to the returned value from the validator

            Assert.Empty(errors);                                           //Check to make sure no errors are returned
            ResetSubscriber();
        }
Exemple #17
0
        [InlineData("*****@*****.**")] //A valid email
        public void isValidEmail_ValidEmail_NoErrorsReturned(String email)
        {
            subscriber.email = email;                                       //Set the attribute to the string being passed in
            var errors = ClassValidator <Subscriber> .Validate(subscriber); //Set errors to the return value from the validator

            Assert.Empty(errors);                                           //Check to make sure no errors are returned
            ResetSubscriber();                                              //reset the subscriber
        }
        public static IEnumerable <ValidationResult> Validate(this CreditCardModel requestData)
        {
            var validationResults = new List <ValidationResult>();

            validationResults.AddRange(ClassValidator <CreditCardModel> .Validate(requestData));

            return(validationResults);
        }
Exemple #19
0
        public void isValidIsBusiness_ValidIsBusiness_NoErrorsReturned(bool isBusiness)
        {
            subscriber.isBusiness = isBusiness;                             //Set the attribute to the boolean being passed in
            var errors = ClassValidator <Subscriber> .Validate(subscriber); //Set errors to the returned value from the validator

            Assert.Empty(errors);                                           //Check to make sure no errors are returned
            ResetSubscriber();
        }
Exemple #20
0
        [InlineData("AAAG_mail.com")] // A invalid format
        public void isValidEmail_InvalidEmail_ErrorReturned(String email)
        {
            subscriber.email = email;                                              //Set the attribute to the string being passed in
            var errors = ClassValidator <Subscriber> .Validate(subscriber);        //Set errors to the return value from the validator

            Assert.Single(errors);                                                 //make sure only a single error is returned
            Assert.Equal("Must be a valid email address", errors[0].ErrorMessage); //Make sure the error message is the correct one
            ResetSubscriber();                                                     //reset the subscriber
        }
Exemple #21
0
        [InlineData(-1)]//invalid
        public void isValidBillingLocation_InvalidBillingLocation_ErrorReturned(int locationID)
        {
            subscriber.billingLocationID = locationID;                           //Set the attribute to the int being passed in
            var errors = ClassValidator <Subscriber> .Validate(subscriber);      //Set errors to the returned value from the validator

            Assert.Single(errors);                                               //Make sure a single error is returned
            Assert.Equal("Must be a valid Location ID", errors[0].ErrorMessage); //Make sure the error returned is the proper error
            ResetSubscriber();
        }
        public void AllowMoreThanOne()
        {
            var e = new WithRegEx {
                Value = "aaa"
            };
            var ca = new ClassValidator(typeof(WithRegEx));
            var iv = ca.GetInvalidValues(e).ToArray();

            ActionAssert.NotThrow(() => iv = ca.GetInvalidValues(e).ToArray());
        }
Exemple #23
0
        public void WhenTagIsSpecified_ValidatePotentialValueForGivenTags()
        {
            IClassValidator cv = new ClassValidator(typeof(EntityForPotential));

            cv.GetPotentialInvalidValues("Value", "123", typeof(Warning)).Should().Have.Count.EqualTo(1);
            cv.GetPotentialInvalidValues("Value", "", typeof(Warning)).Should().Have.Count.EqualTo(2);
            cv.GetPotentialInvalidValues("Value", "", typeof(Error), typeof(Warning)).Should().Have.Count.EqualTo(2);
            cv.GetPotentialInvalidValues("Value", "123", typeof(Error)).Should().Be.Empty();
            cv.GetPotentialInvalidValues("Value", "", typeof(Error)).Should().Have.Count.EqualTo(1);
        }
Exemple #24
0
        public void WhenTagIsSpecified_ValidateRelationForGivenTags()
        {
            // specifying [Valid] the relation is always analized
            IClassValidator cv = new ClassValidator(typeof(EntityWithReletion));

            cv.GetInvalidValues(new EntityWithReletion {
                Reference = new Entity()
            }, typeof(Error)).Should().Have.Count.EqualTo(1);
            cv.GetInvalidValues(new EntityWithReletion {
                Reference = new Entity()
            }, typeof(Error), null).Should().Have.Count.EqualTo(2);
        }
Exemple #25
0
        void ValidateRecursive(Root root, Expression expression)
        {
            if (expression is Class)
            {
                ClassValidator.Validate(this, root, expression as Class);
            }

            foreach (var child in expression.ChildExpressions)
            {
                ValidateRecursive(root, child);
            }
        }
Exemple #26
0
        public void WhenNoTagIsSpecified_AllTagsMatch()
        {
            // all propeties are wrong
            IClassValidator cv            = new ClassValidator(typeof(aEntity));
            var             invalidValues = cv.GetInvalidValues(new aEntity {
                ValueMinMax = 101
            }).ToArray();

            invalidValues.First(iv => iv.PropertyName == "ValueMinMax").MatchTags.Should().Have.SameValuesAs("error", "warning");
            invalidValues.First(iv => iv.PropertyName == "ValueMin").MatchTags.Should().Have.SameValuesAs("warning", "information");
            invalidValues.First(iv => iv.PropertyName == "ValueWithoutTags").MatchTags.Should().Have.Count.EqualTo(0);
        }
Exemple #27
0
        public void ClassValidator_customgetter_ok()
        {
            ClassValidator <Row> validator = ClassValidator <Row>
                                             .Init()
                                             .For(x => x.Key, x => x.Key.ToUpper(), p => p.IsNotNullOrEmpty().IsStringValues(new string[] { "MYKEY" }))
                                             .Validate(new Row()
            {
                Key = "mykey", DateTimeValue = null
            });

            Assert.Empty(validator.ValidationErrors);
        }
Exemple #28
0
        public void ClassValidator_list_with_index()
        {
            var defaultList = new List <Row>()
            {
                new Row()
                {
                    Key = "mykey", DateTimeValue = "20181201"
                },
                new Row()
                {
                    Key = "mykey", DateTimeValue = "20181301"
                },                                                       // error
                new Row()
                {
                    Key = "mykey", DateTimeValue = null
                }                                                 // error
            };

            ClassValidator <Row> CreateValidator(ClassValidatorOption option, List <Row> list)
            {
                return(ClassValidator <Row>
                       .Init(option) // show index in error list. default index
                       .For(x => x.Key, p => p.IsNotNull())
                       .For(x => x.DateTimeValue, p => p.IsNotNull().TryParseDateTime("yyyyMMdd"))
                       .ValidateList(list));
            }

            // show index in error list. default index
            ClassValidator <Row> validator = CreateValidator(
                new ClassValidatorOption()
            {
                ShowRowIndex = true
            },
                defaultList
                );

            Assert.Equal(3, validator.ValidationErrors.Count);
            Assert.Contains("Row 2 ", validator.ValidationErrors[0].ErrorMessage);
            Assert.Contains("Row 3 ", validator.ValidationErrors[1].ErrorMessage);

            // show index in error list. force index
            ClassValidator <Row> validatorForceIndex = CreateValidator(
                new ClassValidatorOption()
            {
                ShowRowIndex = true, RowIndexStartsAt = 5
            },
                defaultList
                );

            Assert.Equal(3, validatorForceIndex.ValidationErrors.Count);
            Assert.Contains("Row 6 ", validatorForceIndex.ValidationErrors[0].ErrorMessage);
            Assert.Contains("Row 7 ", validatorForceIndex.ValidationErrors[1].ErrorMessage);
        }
Exemple #29
0
        public void ClassValidator_oneerror()
        {
            ClassValidator <Row> validator = ClassValidator <Row>
                                             .Init()
                                             .For(x => x.Key, p => p.IsNotNull())
                                             .For(x => x.DateTimeValue, p => p.IsNotNull()) // error
                                             .Validate(new Row()
            {
                Key = "mykey", DateTimeValue = null
            });

            Assert.Single(validator.ValidationErrors);
        }
Exemple #30
0
        public void ValidatableElementTest()
        {
            ClassValidator     cv = new ClassValidator(typeof(Address));
            ValidatableElement ve = new ValidatableElement(typeof(Address), cv);

            Assert.AreEqual(ve.EntityType, typeof(Address));
            Assert.IsTrue(ReferenceEquals(cv, ve.Validator));
            Assert.IsNull(ve.Getter);
            Assert.IsFalse(ve.SubElements.GetEnumerator().MoveNext());
            Assert.IsTrue(ve.Equals(new ValidatableElement(typeof(Address), new ClassValidator(typeof(Address)))));
            Assert.IsFalse(ve.Equals(5));             // any other obj
            Assert.AreEqual(ve.GetHashCode(),
                            (new ValidatableElement(typeof(Address), new ClassValidator(typeof(Address)))).GetHashCode());
        }