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;
            }
        }
        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);
        }
        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");
        }
        public static IEnumerable <ValidationResult> Validate(this CreditCardModel requestData)
        {
            var validationResults = new List <ValidationResult>();

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

            return(validationResults);
        }
        public void Valid_Object_Will_Return_Correct_Result()
        {
            // arrange
            setupBasicProfile();
            var model = new Model1
            {
                Name = "Jon Hawkins",
                Age  = 21
            };

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

            // assert
            result.Success.Should().BeTrue();
            result.Errors.Count.Should().Be(0);
        }
예제 #6
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();
        }
예제 #7
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
        }
예제 #8
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
        }
예제 #9
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();
        }
예제 #10
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();
        }
예제 #11
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
        }
예제 #12
0
        public async Task <IActionResult> Create(Class model)
        {
            var validation = _validator.Validate(model);

            if (!validation.IsValid)
            {
                return(BadRequest(validation.Errors));
            }
            return(Ok(await _classService.Add(model)));
        }
예제 #13
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);
            }
        }
        public void isFrequencyValid_ValidRegionFrequency_regionIsCreated(int Frequency)
        {
            DateTime date = DateTime.Today;

            Region rOne = new Region()
            {
                regionName = "South End",
                frequency  = Frequency,
                firstDate  = new DateTime(date.Year + 1, 1, 1)
            };

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

            Assert.Empty(results);
        }
        public void isRegionNameValid_validRegionName_RegionCreated(string validName)
        {
            DateTime date = DateTime.Today;

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

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

            Assert.Empty(results);
        }
        public void isValidRegionCreated_ValidRegionWithoutLocations_RegionCreated()
        {
            DateTime date = DateTime.Today;

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

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

            Assert.Empty(results);
        }
        public void isRegionDateValid_ValidRegionFirstDate_RegionIsCreated(int day, int month)
        {
            DateTime date = DateTime.Today;

            Region rOne = new Region()
            {
                regionName = "South End",
                frequency  = 10,
                firstDate  = new DateTime(date.Year + 1, month, day)
            };

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

            Assert.Empty(results);
        }
예제 #18
0
        private static void Main(string[] args)
        {
            // !!! Don't delete this line0
            // Print UTF8 character in console
            Console.OutputEncoding = Encoding.UTF8;
            Info info = new Info("112312312312312Ac", "12/12/2019");

            ClassValidator autoValidator = new ClassValidator(typeof(Info));

            autoValidator.Validate(info).ForEach(
                x => Console.WriteLine(x.IsValid + " " + x.ErrorMessage)
                );

            Console.WriteLine("----------------------------------------");

            autoValidator.ValidateByPropertyName(info, nameof(Info.Name)).ForEach(
                x => Console.WriteLine(x.IsValid + " " + x.ErrorMessage)
                );

            Console.WriteLine("----------------------------------------");

            UserValidator infoValidate = new UserValidator("2", 3);

            infoValidate.Validate().ForEach(
                x => Console.WriteLine(x.IsValid + " " + x.ErrorMessage)
                );

            Console.WriteLine("----------------------------------------");

            infoValidate.ValidateByPropertyName(nameof(UserValidator.Email)).ForEach(
                x => Console.WriteLine(x.IsValid + " " + x.ErrorMessage)
                );

            Console.WriteLine("----------------------------------------");

            FieldValidator validator = RuleBuilder.Create()
                                       .AddRule(new MinLength(8))
                                       .AddRule(new HasUpperCase())
                                       .Build();

            string str = "string need to validate";

            validator.Validate(str).ForEach(
                x => Console.WriteLine(x.IsValid + " " + x.ErrorMessage)
                );

            Console.WriteLine("----------------------------------------");
        }
        public void IsLocationWithoutUnitCreated_ValidLocationNoUnit_LocationCreated()
        {
            Location loc = new Location
            {
                locationID   = 3,
                city         = "Flavortown",
                locationType = "pickup",
                postalCode   = "S0K 1M0",
                province     = "Saskatchewan",
                address      = "123 street"
            };

            var errors = ClassValidator <Location> .Validate(loc); //Set errors to the returned value from the validator

            Assert.Empty(errors);                                  //Check to make sure no errors are returned
        }
        public void isRegionCreatedWithStatus_RegionWithStatus_RegionIsCreated()
        {
            DateTime date = DateTime.Today;

            Region rOne = new Region()
            {
                regionName = "South End",
                frequency  = 10,
                firstDate  = new DateTime(date.Year + 1, 1, 1),
                inactive   = false
            };

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

            Assert.Empty(results);
        }
        public void isFrequencyInvalid_InvalidRegionFrequency_ErrorReturnedRegionNotCreated(int Frequency)
        {
            DateTime date = DateTime.Today;

            Region rOne = new Region()
            {
                regionName = "South End",
                frequency  = Frequency,
                firstDate  = new DateTime(date.Year + 1, date.Month, date.Day)
            };

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

            Assert.Single(results);

            Assert.Equal("Region frequency must be between 1 and 52", results[0].ToString());
        }
        public void IsUnitAddressLengthRestricted_UnitAddressTooLong_ErrorReturned(string sUnit)
        {
            string   sCharError = "Unit/Apt. cannot exceed 15 characters in length";
            Location loc        = new Location
            {
                locationID   = 3,
                city         = "Flavortown",
                unit         = sUnit,
                locationType = "pickup",
                postalCode   = "S0K1M0",
                province     = "Saskatchewan",
                address      = "123 street"
            };

            var errors = ClassValidator <Location> .Validate(loc); //Set errors to the returned value from the validator

            Assert.Equal(sCharError, errors[0].ErrorMessage);      //Check to make sure no errors are returned
        }
        public void Profile_Alt_Passing_With_Whole_Object_valid_Age_Success()
        {
            // arrange
            var profile = new ProfileWithWholeObjectAgeToStringEqualLengthOfName();
            var model   = new Model1
            {
                Age  = 5,
                Name = "Jon h"
            };

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

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

            // assert
            result.Success.Should().BeTrue();
        }
예제 #24
0
        [InlineData(499)] //not stored ID
        public void isValidLocationID_InvalidLocationID_ErrorReturned(int locationID)
        {
            Location newBilling = new Location()
            {
                locationID   = 500,
                city         = "saskatoon",
                locationType = "billing",
                postalCode   = "S0K 1M0",
                province     = "Saskatchewan",
                address      = "123 street"
            };

            subscriber.billingLocation = newBilling;
            var errors = ClassValidator <Subscriber> .Validate(subscriber);      //Set errors to the returned value from the validator

            Assert.Single(errors);                                               //Check that one error is returned
            Assert.Equal("Must be a valid Location ID", errors[0].ErrorMessage); //check to make sure the error message is correct
            ResetSubscriber();
        }
예제 #25
0
        [InlineData(3)] //Valid case
        public void isValidBillingLocation_ValidBillingLocation_NoErrorsReturned(int locationID)
        {
            Location newBilling = new Location()
            {
                locationID   = 3,
                city         = "saskatoon",
                locationType = "pickup",
                postalCode   = "S0K1M0",
                province     = "Saskatchewan",
                address      = "123 street"
            };

            subscriber.billingLocation   = newBilling;
            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.Empty(errors);                                           //Check to make sure no errors are returned
            ResetSubscriber();
        }
        public void IsUnitWithSpecialCharactersCreated_UnitWithSpecialCharacters_ErrorReturned(string sUnit)
        {
            string sCharError = "Unit/Apt. can only contain letters, numbers, and the - symbol";

            Location loc = new Location
            {
                locationID   = 3,
                city         = "Flavortown",
                unit         = sUnit,
                locationType = "pickup",
                postalCode   = "S0K 1M0",
                province     = "Saskatchewan",
                address      = "123 street"
            };

            var errors = ClassValidator <Location> .Validate(loc); //Set errors to the returned value from the validator

            Assert.Equal(sCharError, errors[0].ErrorMessage);      //Check to make sure no errors are returned
        }
        public void Using_Invalid_Email_Can_Be_Displayed_In_Error_Message()
        {
            // arrange
            var profile = new EmailCustomErrorMessageWithValue();

            var model = new Model2
            {
                EmailAddress = "jon.hawkins"
            };

            var validator = new ClassValidator <Model2>(profile.MappingExpressions.OfType <IMappingExpression <Model2> >().Single(), _settings);

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

            // assert
            result.Success.Should().BeFalse();
            result.Errors.Should().ContainKey("EmailAddress");
            result.Errors["EmailAddress"].Should().Contain("jon.hawkins is not a valid email address");
        }
        public void Null_Checks_With_Values_Pass()
        {
            // arrange
            var profile = new NullItemMappingProfile();

            var model = new NullableModel
            {
                Model1       = new Model1(),
                EmailAddress = "e",
                Number       = 22,
                AreYouHappy  = true
            };

            var validator = new ClassValidator <NullableModel>(profile.MappingExpressions.OfType <IMappingExpression <NullableModel> >().Single(), _settings);

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

            // assert
            result.Success.Should().BeTrue();
        }
        public void Null_Checks_Catch_Errors()
        {
            // arrange
            var profile = new NullItemMappingProfile();

            var model = new NullableModel();

            var validator = new ClassValidator <NullableModel>(profile.MappingExpressions.OfType <IMappingExpression <NullableModel> >().Single(), _settings);

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

            // assert
            result.Success.Should().BeFalse();
            result.Errors.Should().ContainKey("EmailAddress");
            result.Errors["EmailAddress"].Should().Contain("EmailAddress Is Null");

            result.Errors.Should().ContainKey("AreYouHappy");
            result.Errors["AreYouHappy"].Should().Contain("AreYouHappy Is Null");

            result.Errors.Should().ContainKey("Number");
            result.Errors["Number"].Should().Contain("Number Is Null");
        }
        public void Profile_With_Expression_That_Calls_A_Method_Gets_Correct_Error_Message()
        {
            // arrange
            var profile = new ProfileWithWholeObject();
            var model   = new Model2
            {
                Number       = 3,
                EmailAddress = "*****@*****.**", // index of the @ is greater than the number should fail
            };

            var validator = new ClassValidator <Model2>(profile.MappingExpressions.OfType <IMappingExpression <Model2> >().Single(), _settings);

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

            // assert
            result.Success.Should().BeFalse();
            result.Errors.Should().ContainKey("Number");
            var numErrors = result.Errors["Number"];

            numErrors.Count.Should().Be(1);
            numErrors.Should().Contain(e => e == "Number should be at least 16");
        }