Пример #1
0
        public void NotNullOrEmptyValidator_PassesNotNull()
        {
            IValidationRule rule = ValidationBuilder.Create().NotNullOrEmpty().Validator;

            var result1 = rule.Validate("dsfj;kdsf");
            var result2 = rule.Validate(new object());

            Assert.True(result1.IsValid);
            Assert.True(result2.IsValid);
        }
Пример #2
0
        public void NotNullOrEmptyValidator_FailsForNullOrEmpty()
        {
            IValidationRule rule = ValidationBuilder.Create().NotNullOrEmpty().Validator;

            var result1 = rule.Validate(null);
            var result2 = rule.Validate(string.Empty);
            var result3 = rule.Validate("");

            Assert.False(result1.IsValid);
            Assert.False(result2.IsValid);
            Assert.False(result3.IsValid);
        }
Пример #3
0
        public void LengthValidator_ValidateExact()
        {
            IValidationRule rule = ValidationBuilder.Create().Length(3).Validator;

            var result1 = rule.Validate("124");
            var result2 = rule.Validate("1234");
            var result3 = rule.Validate(123);
            var result4 = rule.Validate("1");

            Assert.True(result1.IsValid);
            Assert.False(result2.IsValid);
            Assert.False(result3.IsValid);
            Assert.False(result4.IsValid);
        }
Пример #4
0
        /// <summary>
        /// Performs the given validation rule for the specified property.
        /// </summary>
        /// <param name="rule">The rule.</param>
        /// <param name="property">The property.</param>
        /// <param name="validationProxy">A validation proxy can be specified.
        /// When supplied, the validation rule and any errors associated with it will be stored within the proxy object instead of this instance.</param>
        /// <exception cref="System.ArgumentNullException">
        /// PerformValidation requires a registered property to be specified.
        /// or
        /// PerformValidation requires a registered property to be specified.
        /// </exception>
        public void PerformValidation(IValidationRule rule, string property, IValidatable validationProxy = null)
        {
            PropertyInfo propertyInfo = null;

            if (string.IsNullOrEmpty(property))
            {
                throw new ArgumentNullException("PerformValidation requires a registered property to be specified.");
            }
            else
            {
                propertyInfo = ValidatableBase.PropertyValidationCache[this.GetType()]
                               .FirstOrDefault(kv => kv.Key.Name.Equals(property)).Key;
            }

            if (propertyInfo == null)
            {
                throw new ArgumentNullException("PerformValidation requires a registered property to be specified.");
            }

            if (validationProxy != null && validationProxy is IValidatable)
            {
                var proxy = validationProxy as IValidatable;
                proxy.PerformValidation(rule, propertyInfo.Name);
            }
            else
            {
                IValidationMessage result = rule.Validate(propertyInfo, this);
                if (result != null)
                {
                    this.AddValidationMessage(result, propertyInfo.Name);
                }
            }
        }
Пример #5
0
        public void LengthValidator_ValidateRange()
        {
            IValidationRule rule = ValidationBuilder.Create().Length(3, 5).Validator;

            var result1 = rule.Validate("12");
            var result2 = rule.Validate("123");
            var result3 = rule.Validate("1234");
            var result4 = rule.Validate("12345");
            var result5 = rule.Validate("123456");

            Assert.False(result1.IsValid);
            Assert.True(result2.IsValid);
            Assert.True(result3.IsValid);
            Assert.True(result4.IsValid);
            Assert.False(result5.IsValid);
        }
Пример #6
0
        public void Validate(string path, Schema schema, object value, List <ValidationResult> results)
        {
            if (_rule == null)
            {
                return;
            }

            var localResults = new List <ValidationResult>();

            _rule.Validate(path, schema, value, localResults);

            if (localResults.Count > 0)
            {
                return;
            }

            results.Add(
                new ValidationResult(
                    path,
                    ValidationResultType.Error,
                    "NOT_FAILED",
                    "Negative check failed",
                    null,
                    null
                    )
                );
        }
        private void HandleValidationRule(
            ChangeOfChargesMessage changeOfChargesMessage,
            IValidationRule validationRule,
            HubRequestValidationResult validationResult)
        {
            const string unknownServerError = "Unknown server error";

            try
            {
                if (_ruleConfigurations == null)
                {
                    validationResult.Add(new ValidationError("VR900", unknownServerError));
                    _logger.LogError($"{nameof(_ruleConfigurations)} was null");
                    return;
                }

                var ruleValidationResult = validationRule.Validate(changeOfChargesMessage, _ruleConfigurations);

                if (ruleValidationResult.ValidatedSuccessfully is false)
                {
                    validationResult.Add(ruleValidationResult.ValidationError);
                }
            }
            catch (RuleNotFoundException ruleNotFoundException)
            {
                validationResult.Add(new ValidationError("VRXYZ", unknownServerError));
                _logger.LogError(ruleNotFoundException, "Rule configuration could not be found");
            }
            catch (RuleCouldNotBeMappedException ruleCouldNotBeMappedException)
            {
                validationResult.Add(new ValidationError("VRXYZ", unknownServerError));
                _logger.LogError(ruleCouldNotBeMappedException, "Rule value could not be mapped");
            }
        }
Пример #8
0
        public void PathValidator_DirectoryValidation()
        {
            IValidationRule rule = ValidationBuilder.Create().Directory().Validator;

            string dir = "TestDirectory";

            Directory.CreateDirectory(dir);
            var result1 = rule.Validate(dir);

            Assert.True(result1.IsValid);


            Directory.Delete(dir);
            var result2 = rule.Validate(dir);

            Assert.False(result2.IsValid);
        }
Пример #9
0
 public async Task ValidateRule <TValidationRule, TViewModel>(IValidationRule <TViewModel> validationRule, TViewModel viewModel)
     where TValidationRule : class, IValidationRule <TViewModel>
     where TViewModel : class
 {
     if (validationRule != null)
     {
         await validationRule.Validate(viewModel);
     }
 }
Пример #10
0
        public bool Validate()
        {
            Errors.Clear();

            IsValid = validation.Validate(this);
            // Errors = validation.ErrorMessages.ToList();

            return(this.IsValid);
        }
Пример #11
0
        public void Validation_should_be_false()
        {
            IValidationRule <string> mockRule = A.Fake <IValidationRule <string> >();

            A.CallTo(() => mockRule.Validate(A <string> ._)).Returns(false);
            ValidatableObject <string> stringObject = new ValidatableObject <string>(mockRule);

            stringObject.Validate();
            stringObject.IsValid.Should().BeFalse();
        }
Пример #12
0
        private void listpicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListPickerValidationControl control = (ListPickerValidationControl)sender;

            if (control.SelectedItem != null)
            {
                IValidationRule v = (IValidationRule)control.ValidationRule;
                control.IsValid = v.Validate(((CustomListBoxItem <Person>)control.SelectedItem).Value == "Choose ..." ? "" : "valid");;
            }
        }
Пример #13
0
        public void ErrorMessage_should_be_equal_to_given_message()
        {
            string message = "The error message of the rule";
            IValidationRule <string> mockValidationRule = A.Fake <IValidationRule <string> >();

            A.CallTo(() => mockValidationRule.Message).Returns(message);
            A.CallTo(() => mockValidationRule.Validate(A <string> ._)).Returns(false);
            ValidatableObject <string> stringObject = new ValidatableObject <string>(mockValidationRule);

            stringObject.Messages.Should().Contain(message);
        }
Пример #14
0
        public void PathValidator_FileValidation()
        {
            IValidationRule rule = ValidationBuilder.Create().File().Validator;

            string filename = "test.txt";

            var stream = File.Create(filename);

            stream.Close();
            stream.Dispose();
            var result1 = rule.Validate(filename);

            Assert.True(result1.IsValid);


            File.Delete(filename);
            var result2 = rule.Validate(filename);

            Assert.False(result2.IsValid);
        }
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var isValid      = false;
            var errorMessage = "";

            ValidationRule.Validate(value, out isValid, out errorMessage);

            var result = new ValidationResult(isValid, errorMessage);

            return(result);
        }
Пример #16
0
        protected override void OnLostFocus(RoutedEventArgs e)
        {
            bool            isInputValid   = true;
            IValidationRule validationRule = this.ValidationRule;

            if (validationRule != null)
            {
                isInputValid = validationRule.Validate(this.Text);
            }
            this.IsValid = isInputValid;

            base.OnLostFocus(e);
        }
Пример #17
0
 /// <summary>
 /// Check if validation rule is valid
 /// </summary>
 private void CheckRule(IValidationRule validationRule)
 {
     if (!validationRule.Validate())
     {
         if (validationRule.ValidationType == ValidationType.Error)
         {
             ValidationResult.Errors.Add(validationRule.GetMessage());
         }
         else
         {
             ValidationResult.Warnings.Add(validationRule.GetMessage());
         }
     }
 }
        /// <summary>
        /// Executes the validation rule supplied for the specified property.
        /// </summary>
        /// <param name="rule">The rule.</param>
        /// <param name="property">The property.</param>
        /// <param name="validationProxy">The validation proxy.</param>
        private void PerformValidation(IValidationRule rule, PropertyInfo property, IValidatable validationProxy = null)
        {
            if (validationProxy != null && validationProxy is ValidatableBase)
            {
                var proxy = validationProxy as ValidatableBase;
                proxy.PerformValidation(rule, property);
            }

            var result = rule.Validate(property, this);

            if (result != null)
            {
                AddValidationMessage(result, property.Name);
            }
        }
Пример #19
0
        /// <summary>
        /// Validates an entity against all validations defined for the entity.
        /// </summary>
        /// <param name="entity">The <typeparamref name="TEntity"/> to validate.</param>
        /// <returns>A <see cref="ValidationResult"/> that contains the results of the validation.</returns>
        public ValidationResult Validate(TEntity entity)
        {
            ValidationResult result = new ValidationResult();

            _validations.Keys.ForEach(x =>
            {
                IValidationRule <TEntity> rule = _validations[x];
                if (!rule.Validate(entity))
                {
                    result.AddError(new ValidationError(rule.ValidationMessage,
                                                        rule.ValidationProperty));
                }
            });
            return(result);
        }
Пример #20
0
        public bool Validate(string property, string propertyName, out ICollection <string> validationErrors)
        {
            switch (propertyName)
            {
            case "Login":
                _validationRule = new LoginValidationRule();
                break;

            case "Password":
                _validationRule = new PasswordValidationRule();
                break;

            default:
                break;
            }
            return(_validationRule.Validate(property, out validationErrors));
        }
Пример #21
0
        public void One_ErrorMessages_should_be_equal_to_given_messages()
        {
            string messageMail   = "The mail message of the rule";
            string messageLength = "The length message of the rule";
            IValidationRule <string> mockMailRule = A.Fake <IValidationRule <string> >();

            A.CallTo(() => mockMailRule.Message).Returns(messageMail);
            A.CallTo(() => mockMailRule.Validate(A <string> ._)).Returns(false);
            IValidationRule <string> mockLengthRule = A.Fake <IValidationRule <string> >();

            A.CallTo(() => mockLengthRule.Message).Returns(messageLength);
            A.CallTo(() => mockLengthRule.Validate(A <string> ._)).Returns(true);
            ValidatableObject <string> stringObject = new ValidatableObject <string>(mockMailRule, mockLengthRule);

            stringObject.Messages.Should().Contain(messageMail);
            stringObject.Messages.Should().NotContain(messageLength);
        }
Пример #22
0
 public void ValidateObject(object sender, EventArgs e, UIElementCollection UIElements, List <ListPickerValidationControl> listpickers)
 {
     foreach (UIElement ui in UIElements)
     {
         if (ui.GetType() == typeof(ValidationControl))
         {
             ValidationControl control = (ValidationControl)ui;
             IValidationRule   v       = (IValidationRule)control.ValidationRule;
             IsPageValid     = v.Validate(control.Text);
             control.IsValid = IsPageValid;
         }
         else if (ui.GetType() == typeof(ListPickerValidationControl))
         {
             ListPickerValidationControl control = (ListPickerValidationControl)ui;
             IValidationRule             v       = (IValidationRule)control.ValidationRule;
             IsPageValid     = v.Validate(((ICustomListBox)control.SelectedItem).Value == "Choose ..." ? "" : "valid");
             control.IsValid = IsPageValid;
         }
     }
 }
Пример #23
0
        /// <summary>
        /// Executes the validation rule supplied for the specified property.
        /// </summary>
        /// <param name="rule">The rule.</param>
        /// <param name="property">The property.</param>
        /// <param name="validationProxy">The validation proxy.</param>
        private void PerformValidation(IValidationRule rule, PropertyInfo property, IValidatable validationProxy = null)
        {
            if (validationProxy != null && validationProxy is ValidatableBase)
            {
                var proxy = validationProxy as ValidatableBase;
                proxy.PerformValidation(rule, property);
            }

            IValidationMessage result = null;

            try
            {
                result = rule.Validate(property, this);
            }
            catch (Exception)
            {
                throw;
            }

            if (result != null)
            {
                this.AddValidationMessage(result, property.Name);
            }
        }
Пример #24
0
 public Option <TNewError> Validate(TValue value)
 => _validationRule
 .Validate(value)
 .Map(_mapError);
Пример #25
0
        public override void Evaluate()
        {
            var valid = !_rule.Validate();

            RuleState.AddMessage(!valid, ResourceName, new NotAllowedByRule());
        }