Exemple #1
0
        public void TestGetMessage()
        {
            SimpleMessageProducer messageProducer = new SimpleMessageProducer();
            IValidationMessage    message         = messageProducer.GetMessage(new DocumentoError(DocumentoError.DocumentoErrorEnum.INVALID_CHECK_DIGITS));

            Assert.AreEqual("DocumentoError : INVALID CHECK DIGITS", message.GetMessage());
        }
        /// <summary>
        /// Validates the specified property.
        /// </summary>
        /// <param name="property">The property that will its value validated.</param>
        /// <param name="sender">The sender who owns the property.</param>
        /// <returns>
        /// Returns a validation message if validation failed. Otherwise null is returned to indicate a passing validation.
        /// </returns>
        public override IValidationMessage Validate(PropertyInfo property, IValidatable sender)
        {
            if (!CanValidate(sender))
            {
                return(null);
            }

            // Set up localization if available.
            PrepareLocalization();

            var validationMessage = Activator.CreateInstance(ValidationMessageType, FailureMessage) as IValidationMessage;
            var value             = property.GetValue(sender, null) ?? string.Empty;

            // While we do convert it to a string below, we want to make sure that the actual Type is a string
            // so that we are not doing a string length comparison check on ToString() of a concrete Type that is not a string.
            IValidationMessage result = null;

            if (value is string)
            {
                var    valStr  = (string)value;
                string pattern = @"^(?!.)(""([^""r\]|\[""r\])*""|"
                                 + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!.).)*)(?<!.)"
                                 + @"@[a-z0-9][w.-]*[a-z0-9].[a-z][a-z.]*[a-z]$";

                Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

                result = regex.IsMatch(valStr) ? validationMessage : null;
            }

            return(RunInterceptedValidation(sender, property, result));
        }
Exemple #3
0
        /// <summary>
        /// Validates the specified property.
        /// </summary>
        /// <param name="property">The property that will its value validated.</param>
        /// <param name="sender">The sender who owns the property.</param>
        /// <returns>
        /// Returns a validation message if validation failed. Otherwise null is returned to indicate a passing validation.
        /// </returns>
        public override IValidationMessage Validate(PropertyInfo property, IValidatable sender)
        {
            if (!CanValidate(sender))
            {
                return(null);
            }

            // Set up localization if available.
            PrepareLocalization();

            var validationMessage = Activator.CreateInstance(ValidationMessageType, FailureMessage) as IValidationMessage;
            var value             = property.GetValue(sender, null) ?? string.Empty;

            // While we do convert it to a string below, we want to make sure that the actual Type is a string
            // so that we are not doing a string length comparison check on ToString() of a concrete Type that is not a string.
            IValidationMessage result = null;

            if (value is string)
            {
                var valStr = (string)value;

                Regex regex = new Regex(@"[0-9]{8,20}", RegexOptions.CultureInvariant);
                //^+?[0 - 9]{ 0, 3 }[\\(]{ 0,1} ([0 - 9]){ 3}[\\)]{0,1}[ ]?([^0-1]){1}([0-9]){2}[ ]?[-]?[ ]?([0-9]){4}[ ]*((x){0,1}([0-9]){1,5}){0,1}&

                result = !regex.IsMatch(valStr) ? validationMessage : null;
            }

            return(RunInterceptedValidation(sender, property, result));
        }
        /// <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);
                }
            }
        }
Exemple #5
0
        private IValidationMessage ValidatePasswordFormat(IValidationMessage failureMessage, PropertyInfo property)
        {
            string regExp = @"^[a-zA-Z0-9\s]+$";

            return(Regex.IsMatch(this.Password, regExp)
                ? null
                : failureMessage);
        }
Exemple #6
0
        /// <summary>
        /// Validates the specified property.
        /// </summary>
        /// <param name="property">The property that will its value validated.</param>
        /// <param name="sender">The sender who owns the property.</param>
        /// <returns>
        /// Returns a validation message if validation failed. Otherwise null is returned to indicate a passing validation.
        /// </returns>
        /// <exception cref="System.MissingMethodException"></exception>
        public override IValidationMessage Validate(System.Reflection.PropertyInfo property, IValidatable sender)
        {
            if (!this.CanValidate(sender))
            {
                return(null);
            }

            // Set up localization if available.
            this.PrepareLocalization();

            // Create an instance of our validation message and return it if there is not a delegate specified.
            IValidationMessage validationMessage = Activator.CreateInstance(this.ValidationMessageType, this.FailureMessage) as IValidationMessage;

            if (string.IsNullOrEmpty(this.DelegateName))
            {
                return(validationMessage);
            }

            // Find our delegate method.
            IEnumerable <MethodInfo> validationMethods = sender
                                                         .GetType()
                                                         .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)
                                                         .Where(m => m.GetCustomAttributes(typeof(ValidationCustomHandlerDelegate), true).Any());

            MethodInfo validationDelegate = validationMethods.FirstOrDefault(m => m
                                                                             .GetCustomAttributes(typeof(ValidationCustomHandlerDelegate), true)
                                                                             .FirstOrDefault(del => (del as ValidationCustomHandlerDelegate).DelegateName == this.DelegateName) != null);

            if (validationDelegate == null)
            {
                throw new MissingMemberException(
                          string.Format("Missing {0} validation delegate for {1} instance.", this.DelegateName, sender.GetType()));
            }

            // Attempt to invoke our delegate method.
            object result = null;

            try
            {
                result = validationDelegate.Invoke(sender, new object[] { validationMessage, property });
            }
            catch (Exception)
            {
                throw;
            }

            // Return the results of the delegate method.
            if (result != null && result is IValidationMessage)
            {
                return(result as IValidationMessage);
            }
            else if (result == null)
            {
                return(null);
            }

            return(validationMessage);
        }
Exemple #7
0
 public BaseHandler(
     IValidationMessage validation,
     IMediator mediator,
     TRepository repository
     ) : base(validation, mediator)
 {
     this._repository = repository;
     ConfigureMapper();
 }
Exemple #8
0
        /// <summary>
        /// Determines if the value specified in the ValidateIfMemberValueIsValue is a valid value.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">Can not base validation off of a non-boolean property.</exception>
        public bool CanValidate(IValidatable sender)
        {
            if (string.IsNullOrEmpty(ValidateIfMemberValueIsValid))
            {
                return(true);
            }

            string valueToParse         = string.Empty;
            bool   evaluateInverseValue = false;

            if (ValidateIfMemberValueIsValid.StartsWith("!"))
            {
                evaluateInverseValue = true;
                valueToParse         = ValidateIfMemberValueIsValid.Substring(1);
            }
            else
            {
                valueToParse = ValidateIfMemberValueIsValid;
            }

            bool   result         = false;
            object valueToCompare = GetComparisonValue(sender, valueToParse);

            if (valueToCompare is bool)
            {
                bool.TryParse(valueToCompare.ToString(), out result);
            }
            else if (valueToCompare is string)
            {
                // We can not validate if the string is empty.
                result = !string.IsNullOrWhiteSpace(valueToCompare.ToString());
            }
            else if (valueToCompare is int || valueToCompare is short || valueToCompare is long || valueToCompare is double || valueToCompare is float || valueToCompare is decimal)
            {
                var numberGreaterThanRule = new ValidateNumberIsGreaterThanAttribute();
                numberGreaterThanRule.GreaterThanValue      = "0";
                numberGreaterThanRule.ValidationMessageType = ValidationMessageType;
                numberGreaterThanRule.FailureMessage        = FailureMessage;
                PropertyInfo       property          = GetAlternatePropertyInfo(sender, ValidateIfMemberValueIsValid);
                IValidationMessage validationMessage = numberGreaterThanRule.Validate(property, sender);

                // if we are greater than 0, then we hav a valid value and can validate.
                result = validationMessage == null;
            }
            else if (valueToCompare == null)
            {
                // We can not validate if the object is null.
                result = false;
            }
            else
            {
                result = true;
            }

            return(evaluateInverseValue ? !result : result);
        }
Exemple #9
0
        public PackageValidationResult(PackageValidationResultType type, IValidationMessage message, IReadOnlyList <IValidationMessage> warnings)
        {
            if (type != PackageValidationResultType.Accepted && message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            Type     = type;
            Message  = message;
            Warnings = warnings ?? EmptyList;
        }
Exemple #10
0
        public IValidationMessage IsOpenValidationIntercept(IValidationMessage failureMessage, PropertyInfo property)
        {
            // Is Open is allowed to be false on Sundays.
            if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
            {
                return null;
            }

            // It's not sunday, so return the failure message generated
            // by the attribute.
            return failureMessage;
        }
Exemple #11
0
        /// <summary>
        /// Adds message to the result.
        /// Based on <paramref name="causesInvalidation" />, this message will or will not invalidate future result.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="causesInvalidation">Flag to see if <paramref name="message"/> invalidates future result.</param>
        /// <returns>Self (for fluency).</returns>
        public ValidationResultBuilder Add(IValidationMessage message, bool causesInvalidation)
        {
            Ensure.NotNull(message, "message");
            messages.Add(message);

            if (causesInvalidation)
            {
                isValid = false;
            }

            return(this);
        }
Exemple #12
0
        public IValidationMessage IsOpenValidationIntercept(IValidationMessage failureMessage, PropertyInfo property)
        {
            // Is Open is allowed to be false on Sundays.
            if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
            {
                return(null);
            }

            // It's not sunday, so return the failure message generated
            // by the attribute.
            return(failureMessage);
        }
Exemple #13
0
        public IList <IValidationMessage> GenerateValidationMessages(IList <IInvalidValue> invalidValues)
        {
            IList <IValidationMessage> messages = new List <IValidationMessage>();

            foreach (IInvalidValue invalidValue in invalidValues)
            {
                IValidationMessage message = messageProducer.GetMessage(invalidValue);
                messages.Add(message);
            }

            return(messages);
        }
Exemple #14
0
        public static PackageValidationResult Invalid(IValidationMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            return(new PackageValidationResult(
                       PackageValidationResultType.Invalid,
                       message,
                       warnings: null));
        }
Exemple #15
0
        /// <summary>
        /// Validates the specified property.
        /// </summary>
        /// <param name="property">The property that will its value validated.</param>
        /// <param name="sender">The sender who owns the property.</param>
        /// <returns>
        /// Returns a validation message if validation failed. Otherwise null is returned to indicate a passing validation.
        /// </returns>
        public override IValidationMessage Validate(PropertyInfo property, IValidatable sender)
        {
            if (!CanValidate(sender))
            {
                return(null);
            }

            // Set up localization if available.
            PrepareLocalization();

            var validationMessage = Activator.CreateInstance(ValidationMessageType, FailureMessage) as IValidationMessage;
            var value             = property.GetValue(sender, null);

            // Check if we need to compare against another property.
            if (!string.IsNullOrEmpty(ComparisonProperty))
            {
                // Fetch the value of the secondary property specified.
                object secondaryPropertyValue = GetComparisonValue(sender, ComparisonProperty);

                if (secondaryPropertyValue != null && !(secondaryPropertyValue is string))
                {
                    int output = 0;
                    if (int.TryParse(secondaryPropertyValue.ToString(), NumberStyles.Integer, null, out output))
                    {
                        GreaterThanValue = output;
                    }
                }
                else if (secondaryPropertyValue != null && secondaryPropertyValue is string)
                {
                    GreaterThanValue = secondaryPropertyValue.ToString().Length;
                }
            }

            if (value == null)
            {
                value = string.Empty;
            }

            // While we do convert it to a string below, we want to make sure that the actual Type is a string
            // so that we are not doing a string length comparison check on ToString() of a concrete Type that is not a string.
            IValidationMessage result = null;

            if (value is string)
            {
                result = (GreaterThanValue > value.ToString().Length || value.ToString().Length == 0) ? validationMessage : null;
            }

            return(RunInterceptedValidation(sender, property, result));
        }
Exemple #16
0
        private IValidationMessage ValidateEmailIsFormatted(IValidationMessage failureMessage, PropertyInfo property)
        {
            string[] addressParts = this.Email.Split('@');

            if (addressParts.Length < 2)
            {
                return(failureMessage);
            }

            string[] domainPiece = addressParts.LastOrDefault().Split('.');
            if (domainPiece.Length < 2)
            {
                return(failureMessage);
            }

            return(null);
        }
Exemple #17
0
        public JsonValidationMessage(IValidationMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (message.HasRawHtmlRepresentation)
            {
                PlainTextMessage = null;
                RawHtmlMessage   = message.RawHtmlMessage;
            }
            else
            {
                PlainTextMessage = message.PlainTextMessage;
                RawHtmlMessage   = null;
            }
        }
Exemple #18
0
 /// <summary>
 /// Creates a new instance set to <see cref="IsValid"/> = true.
 /// </summary>
 public ValidationResult([NotNull] IValidationMessage message)
 {
     _IsValid  = true;
     _Result   = ResultCodes.Ok;
     _Messages = new[]
     {
         message as ValidationMessage ??
         new ValidationMessage(
             message.Severity,
             message.Message,
             message.ResultCode,
             message.ErrorCode,
             message.Kind,
             message.Reference
             )
     };
     _ErrorMessage = _Messages.FirstOrDefault()?.Message;
     _ErrorCode    = _Messages.FirstOrDefault()?.ErrorCode;
 }
        /// <summary>
        /// Validates the specified property via the supplied method delegate.
        /// </summary>
        /// <param name="validationDelegate">The validation delegate.</param>
        /// <param name="failureMessage">The failure message.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="validationProxy">The validation proxy.</param>
        /// <returns>Returns an IMessage if validation was not successful, otherwise null is returned to indicate success.</returns>
        public IValidationMessage ValidateProperty(Func <bool> validationDelegate, IValidationMessage failureMessage, string propertyName, IValidatable validationProxy = null)
        {
            if (validationProxy != null)
            {
                return(validationProxy.ValidateProperty(validationDelegate, failureMessage, propertyName));
            }

            bool passedValidation = validationDelegate();

            if (!passedValidation)
            {
                this.AddValidationMessage(failureMessage, propertyName);
            }
            else
            {
                this.RemoveValidationMessage(failureMessage, propertyName);
            }

            return(!passedValidation ? failureMessage : null);
        }
        /// <summary>
        /// Removes the given validation message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="property">The property.</param>
        public void RemoveValidationMessage(IValidationMessage message, string property)
        {
            if (string.IsNullOrEmpty(property))
            {
                return;
            }

            if (!this.ValidationMessages.ContainsKey(property))
            {
                return;
            }

            if (this.ValidationMessages[property].Any(msg => msg == message || msg.Message.Equals(message.Message)))
            {
                // Remove the error from the key's collection.
                this.ValidationMessages[property].Remove(
                    this.ValidationMessages[property].FirstOrDefault(msg => msg == message || msg.Message.Equals(message.Message)));

                this.OnValidationChanged(new ValidationChangedEventArgs(property, this.ValidationMessages[property]));
            }
        }
Exemple #21
0
        /// <summary>
        /// Validates the specified property.
        /// </summary>
        /// <param name="property">The property that will its value validated.</param>
        /// <param name="sender">The sender who owns the property.</param>
        /// <returns>
        /// Returns a validation message if validation failed. Otherwise null is returned to indicate a passing validation.
        /// </returns>
        public override IValidationMessage Validate(System.Reflection.PropertyInfo property, IValidatable sender)
        {
            if (!this.CanValidate(sender))
            {
                return(null);
            }

            // Set up localization if available.
            this.PrepareLocalization();

            var validationMessage = Activator.CreateInstance(this.ValidationMessageType, this.FailureMessage) as IValidationMessage;
            var value             = property.GetValue(sender, null);

            IValidationMessage result = null;

            if (value is string)
            {
                result = string.IsNullOrWhiteSpace(value.ToString()) ? validationMessage : null;
            }
            else if (value is IEnumerable)
            {
                if (value is ICollection)
                {
                    result = (value as ICollection).Count > 0 ? null : validationMessage;
                }
                else
                {
                    // Only perform the cast if the underlying Type is not an ICollection.
                    result = (value as IEnumerable <object>).Any() ? null : validationMessage;
                }
            }
            else
            {
                result = value == null ? validationMessage : null;
            }

            return(this.RunInterceptedValidation(sender, property, result));
        }
        /// <summary>
        /// Adds a validation message to the instance.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="property">The property.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">property;You must supply a property name when adding a new validation message to this instance.</exception>
        public void AddValidationMessage(IValidationMessage message, string property)
        {
            if (string.IsNullOrEmpty(property))
            {
                throw new ArgumentOutOfRangeException("property", "You must supply a property name when adding a new validation message to this instance.");
            }

            // If the key does not exist, then we create one.
            if (!this.ValidationMessages.ContainsKey(property))
            {
                this.ValidationMessages[property] = new List <IValidationMessage>();
            }

            if (this.ValidationMessages[property].Any(msg => msg.Message.Equals(message.Message) || msg == message))
            {
                return;
            }

            this.ValidationMessages[property].Add(message);

            // Publish our new validation collection for this property.
            this.OnValidationChanged(new ValidationChangedEventArgs(property, this.ValidationMessages[property]));
        }
        /// <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);
            }
        }
Exemple #24
0
 private MessageOperation()
 {
     validationMessage = StaticKernel.Get <IValidationMessage>();
 }
 protected abstract void Validate(IExcelParser blockPlan, out IValidationMessage message, Action next);
Exemple #26
0
        /// <summary>
        /// Validates the minimum float value.
        /// </summary>
        /// <param name="propertyValue">The property value.</param>
        /// <param name="alternateProperty">The alternate property.</param>
        /// <param name="validationMessage">The validation message.</param>
        /// <returns></returns>
        private IValidationMessage ValidateMinimumFloatValue(object propertyValue, object alternateProperty, IValidationMessage validationMessage)
        {
            float convertedValueFromProperty         = 0;
            float convertedMinimumValue              = 0;
            bool  propertyConversionSucceeded        = float.TryParse(propertyValue.ToString(), NumberStyles.Float, null, out convertedValueFromProperty);
            bool  valueComparisonConversionSucceeded = float.TryParse(this.MinimumValue, NumberStyles.Float, null, out convertedMinimumValue);

            if (!propertyConversionSucceeded && !valueComparisonConversionSucceeded && alternateProperty == null)
            {
                throw new InvalidCastException("Validation failed due to invalid data being provided to the validator for conversion.");
            }

            // Compare against our secondary property and the senders property value.
            float alternateValue;

            if (alternateProperty != null &&
                float.TryParse(alternateProperty.ToString(), NumberStyles.Float, null, out alternateValue))
            {
                return(alternateValue <= convertedValueFromProperty ? null : validationMessage);
            }
            else
            {
                // Compare the value to the maximum allowed by the attribute.
                return(convertedMinimumValue <= convertedValueFromProperty ? null : validationMessage);
            }
        }
Exemple #27
0
        private IValidationMessage ValidateEmailIsFormatted(IValidationMessage failureMessage, PropertyInfo property)
        {
            string[] addressParts = this.Email.Split('@');

            if (addressParts.Length < 2)
            {
                return failureMessage;
            }

            string[] domainPiece = addressParts.LastOrDefault().Split('.');
            if (domainPiece.Length < 2)
            {
                return failureMessage;
            }

            return null;
        }
 /// <summary>
 /// Adds a new validation message.
 /// </summary>
 /// <param name="message">Validation message to be added.</param>
 public void AddMessage(IValidationMessage message)
 {
     this.collectedViolations.Add(message);
 }
Exemple #29
0
 public RegistrarTransacaoCashbackCommandHandler(IValidationMessage validation, IMediator mediator, IClienteRepository repository)
     : base(validation, mediator, repository)
 {
 }
Exemple #30
0
        /// <summary>
        /// Validates the specified property.
        /// </summary>
        /// <param name="property">The property that will its value validated.</param>
        /// <param name="sender">The sender who owns the property.</param>
        /// <returns>
        /// Returns a validation message if validation failed. Otherwise null is returned to indicate a passing validation.
        /// </returns>
        public override IValidationMessage Validate(System.Reflection.PropertyInfo property, IValidatable sender)
        {
            if (!this.CanValidate(sender))
            {
                return(null);
            }

            // Set up localization if available.
            this.PrepareLocalization();

            var validationMessage =
                Activator.CreateInstance(this.ValidationMessageType, this.FailureMessage) as IValidationMessage;

            // Get the property value.
            var propertyValue = property.GetValue(sender, null);

            // Ensure the property value is the same data type we are comparing to.
            if (!this.ValidateDataTypesAreEqual(propertyValue))
            {
                var error = string.Format(
                    "The property '{0}' data type is not the same as the data type ({1}) specified for validation checks. They must be the same Type.",
                    property.PropertyType.Name,
                    this.numberDataType.ToString());
                throw new ArgumentNullException(error);
            }

            // Check if we need to compare against another property.
            object alternateProperty = null;

            if (!string.IsNullOrEmpty(this.ComparisonProperty))
            {
                // Fetch the value of the secondary property specified.
                alternateProperty = this.GetComparisonValue(sender, this.ComparisonProperty);
            }

            IValidationMessage result = null;

            if (this.numberDataType == ValidationNumberDataTypes.Short)
            {
                result = ValidateShortValueIsGreaterThan(propertyValue, alternateProperty, validationMessage);
            }
            else if (this.numberDataType == ValidationNumberDataTypes.Int)
            {
                result = this.ValidateIntegerValueIsGreaterThan(propertyValue, alternateProperty, validationMessage);
            }
            else if (this.numberDataType == ValidationNumberDataTypes.Long)
            {
                result = this.ValidateLongValueIsGreaterThan(propertyValue, alternateProperty, validationMessage);
            }
            else if (this.numberDataType == ValidationNumberDataTypes.Float)
            {
                result = this.ValidateFloatValueIsGreaterThan(propertyValue, alternateProperty, validationMessage);
            }
            else if (this.numberDataType == ValidationNumberDataTypes.Double)
            {
                result = this.ValidateDoubleValueIsGreaterThan(propertyValue, alternateProperty, validationMessage);
            }
            else if (this.numberDataType == ValidationNumberDataTypes.Decimal)
            {
                result = this.ValidateDecimalValueIsGreaterThan(propertyValue, alternateProperty, validationMessage);
            }

            return(this.RunInterceptedValidation(sender, property, result));
        }
        /// <summary>
        /// Runs the delegate specified to intercept validation.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="property">The property.</param>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        protected IValidationMessage RunInterceptedValidation(IValidatable sender, PropertyInfo property, IValidationMessage message)
        {
            if (string.IsNullOrWhiteSpace(this.InterceptionDelegate))
            {
                return message;
            }

            var delegateValidationRule = new ValidateWithCustomHandlerAttribute
            {
                DelegateName = this.InterceptionDelegate,
                FailureMessage = message == null ? string.Empty : message.Message,
                ValidationMessageType = message == null ? null : message.GetType(),
            };

            return delegateValidationRule.Validate(property, sender);
        }
Exemple #32
0
        private IValidationMessage ValidatePasswordFormat(IValidationMessage failureMessage, PropertyInfo property)
        {
            string regExp = @"^[a-zA-Z0-9\s]+$";

            return Regex.IsMatch(this.Password, regExp)
                ? null
                : failureMessage;
        }
        /// <summary>
        /// Validates the minimum short value.
        /// </summary>
        /// <param name="propertyValue">The property value.</param>
        /// <param name="alternateProperty">The alternate property.</param>
        /// <param name="validationMessage">The validation message.</param>
        /// <returns></returns>
        private IValidationMessage ValidateMinimumShortValue(object propertyValue, object alternateProperty, IValidationMessage validationMessage)
        {
            short convertedValueFromProperty = 0;
            short convertedComparisonValue = 0;
            bool propertyConversionSucceeded = short.TryParse(propertyValue.ToString(), NumberStyles.Integer, null, out convertedValueFromProperty);
            bool valueComparisonConversionSucceeded = short.TryParse(this.MaximumValue, NumberStyles.Integer, null, out convertedComparisonValue);

            if ((!propertyConversionSucceeded || !valueComparisonConversionSucceeded) && alternateProperty == null)
            {
                throw new InvalidCastException("Validation failed due to invalid data being provided to the validator for conversion. Please ensure the MaximumValue supplied for validation is in the format matching the property's data type.");
            }

            // Compare against our secondary property and the senders property value.
            short alternateValue;
            if (alternateProperty != null &&
                short.TryParse(alternateProperty.ToString(), NumberStyles.Integer, null, out alternateValue))
            {
                return alternateValue >= convertedValueFromProperty ? null : validationMessage;
            }
            else
            {
                // Compare the value to the maximum allowed by the attribute.
                return convertedComparisonValue >= convertedValueFromProperty ? null : validationMessage;
            }
        }
        /// <summary>
        /// Validates the minimum long value.
        /// </summary>
        /// <param name="propertyValue">The property value.</param>
        /// <param name="alternateMaxProperty">The alternate property.</param>
        /// <param name="alternateMinProperty">The alternate minimum property.</param>
        /// <param name="validationMessage">The validation message.</param>
        /// <returns></returns>
        /// <exception cref="InvalidCastException">Validation failed due to invalid data being provided to the validator for conversion.</exception>
        private IValidationMessage ValidateLongInRange(object propertyValue, object alternateMaxProperty, object alternateMinProperty, IValidationMessage validationMessage)
        {
            long convertedValueFromProperty = 0;
            long convertedMaximumValue = 0;
            long convertedMinimumValue = 0;
            bool propertyConversionSucceeded = long.TryParse(propertyValue.ToString(), NumberStyles.Integer, null, out convertedValueFromProperty);
            bool maxValueConversionSucceeded = long.TryParse(this.MaximumValue, NumberStyles.Integer, null, out convertedMaximumValue);
            bool minValueConversionSucceeded = long.TryParse(this.MinimumValue, NumberStyles.Integer, null, out convertedMinimumValue);

            if (!propertyConversionSucceeded && !maxValueConversionSucceeded && !minValueConversionSucceeded && alternateMaxProperty == null)
            {
                throw new InvalidCastException("Validation failed due to invalid data being provided to the validator for conversion.");
            }

            // Compare against our secondary property and the senders property value.
            long maxValue = 0;
            if (alternateMaxProperty != null &&
                !long.TryParse(alternateMaxProperty.ToString(), NumberStyles.Integer, null, out maxValue))
            {
                var error = string.Format(
                    "The property data type is not the same as the data type ({0}) specified for validation checks. They must be the same Type.",
                    this.numberDataType.ToString());
                throw new ArgumentNullException(error);
            }
            else if (maxValue == 0)
            {
                maxValue = convertedMaximumValue;
            }

            long minValue = 0;
            if (alternateMinProperty != null)
            {
                var error = string.Format(
                    "The property data type is not the same as the data type ({0}) specified for validation checks. When validating the range of two other member properties, the data types much all match.",
                    this.numberDataType.ToString());
                throw new ArgumentNullException(error);
            }
            else if (minValue == 0)
            {
                minValue = convertedMinimumValue;
            }

            // Compare the value to the maximum allowed by the attribute.
            return ((minValue <= convertedValueFromProperty) && (maxValue >= convertedValueFromProperty))
                ? null
                : validationMessage;
        }
        /// <summary>
        /// Validates the minimum short value.
        /// </summary>
        /// <param name="propertyValue">The property value.</param>
        /// <param name="alternateMaxProperty">The alternate property.</param>
        /// <param name="alternateMinProperty">The alternate minimum property.</param>
        /// <param name="validationMessage">The validation message.</param>
        /// <returns></returns>
        /// <exception cref="InvalidCastException">Validation failed due to invalid data being provided to the validator for conversion.</exception>
        private IValidationMessage ValidateShortValueInRange(object propertyValue, object alternateMaxProperty, object alternateMinProperty, IValidationMessage validationMessage)
        {
            short convertedValueFromProperty = 0;
            short convertedMaximumValue = 0;
            short convertedMinimumValue = 0;
            bool propertyConversionSucceeded = short.TryParse(propertyValue.ToString(), NumberStyles.Integer, null, out convertedValueFromProperty);
            bool maxValueConversionSucceeded = short.TryParse(this.MaximumValue, NumberStyles.Integer, null, out convertedMaximumValue);
            bool minValueConversionSucceeded = short.TryParse(this.MinimumValue, NumberStyles.Integer, null, out convertedMinimumValue);

            if (!propertyConversionSucceeded && !maxValueConversionSucceeded && !minValueConversionSucceeded && alternateMaxProperty == null)
            {
                throw new InvalidCastException("Validation failed due to invalid data being provided to the validator for conversion.");
            }

            // Compare against our secondary property and the senders property value.
            short maxValue = 0;
            if (alternateMaxProperty != null &&
                !short.TryParse(alternateMaxProperty.ToString(), NumberStyles.Integer, null, out maxValue))
            {
                var error = string.Format(
                    "The property data type is not the same as the data type ({0}) specified for validation checks. They must be the same Type.",
                    this.numberDataType.ToString());
                throw new ArgumentNullException(error);
            }
            else if (maxValue == 0)
            {
                maxValue = convertedMaximumValue;
            }

            short minValue = 0;
            if (alternateMinProperty != null &&
                !short.TryParse(alternateMinProperty.ToString(), NumberStyles.Integer, null, out minValue))
            {
                var error = string.Format(
                    "The property data type is not the same as the data type ({0}) specified for validation checks. They must be the same Type.",
                    this.numberDataType.ToString());
                throw new ArgumentNullException(error);
            }
            else if (minValue == 0)
            {
                // If the conversion in the alternate property conditional check succeeded above, then minValue will not be zero
                // if it is zero, the conversion failed and we use our pre-set property.
                minValue = convertedMinimumValue;
            }

            // Compare the value to the maximum allowed by the attribute.
            return ((minValue <= convertedValueFromProperty) && (maxValue >= convertedValueFromProperty))
                ? null
                : validationMessage;
        }
Exemple #36
0
        /// <summary>
        /// Validates the minimum decimal value.
        /// </summary>
        /// <param name="propertyValue">The property value.</param>
        /// <param name="alternateProperty">The alternate property.</param>
        /// <param name="validationMessage">The validation message.</param>
        /// <returns></returns>
        private IValidationMessage ValidateDecimalValueIsGreaterThan(object propertyValue, object alternateProperty, IValidationMessage validationMessage)
        {
            decimal convertedValueFromProperty         = 0;
            decimal maximumConvertedValue              = 0;
            bool    propertyConversionSucceeded        = decimal.TryParse(propertyValue.ToString(), NumberStyles.Number, null, out convertedValueFromProperty);
            bool    valueComparisonConversionSucceeded = decimal.TryParse(this.LessThanValue, NumberStyles.Number, null, out maximumConvertedValue);

            if (!propertyConversionSucceeded && !valueComparisonConversionSucceeded && alternateProperty == null)
            {
                throw new InvalidCastException("Validation failed due to invalid data being provided to the validator for conversion.");
            }

            // Compare against our secondary property and the senders property value.
            decimal alternateValue;

            if (alternateProperty != null &&
                decimal.TryParse(alternateProperty.ToString(), NumberStyles.Number, null, out alternateValue))
            {
                return(alternateValue > convertedValueFromProperty ? null : validationMessage);
            }
            else
            {
                // Compare the value to the maximum allowed by the attribute.
                return(maximumConvertedValue > convertedValueFromProperty ? null : validationMessage);
            }
        }
Exemple #37
0
 public ObterClienteQueryHandler(IValidationMessage validation, IMediator mediator, IClienteRepository repository)
     : base(validation, mediator, repository)
 {
 }
 protected override void Validate(IExcelParser blockPlan, out IValidationMessage message, Action next)
 {
     Validate(blockPlan, out message, _localization, next);
 }
Exemple #39
0
 public BaseSimpleHandler(IValidationMessage validation, IMediator mediator)
 {
     this._validation = validation;
     this._mediator   = mediator;
 }
        /// <summary>
        /// Validates the minimum short value.
        /// </summary>
        /// <param name="propertyValue">The property value.</param>
        /// <param name="alternateProperty">The alternate property.</param>
        /// <param name="validationMessage">The validation message.</param>
        /// <returns></returns>
        private IValidationMessage ValidateShortValueIsGreaterThan(object propertyValue, object alternateProperty, IValidationMessage validationMessage)
        {
            short convertedValueFromProperty = 0;
            short convertedMinimumValue = 0;
            bool propertyConversionSucceeded = short.TryParse(propertyValue.ToString(), NumberStyles.Integer, null, out convertedValueFromProperty);
            bool valueComparisonConversionSucceeded = short.TryParse(this.GreaterThanValue, NumberStyles.Integer, null, out convertedMinimumValue);

            if (!propertyConversionSucceeded && !valueComparisonConversionSucceeded && alternateProperty == null)
            {
                throw new InvalidCastException("Validation failed due to invalid data being provided to the validator for conversion.");
            }

            // Compare against our secondary property and the senders property value.
            short alternateValue;
            if (alternateProperty != null &&
                short.TryParse(alternateProperty.ToString(), NumberStyles.Integer, null, out alternateValue))
            {
                return alternateValue < convertedValueFromProperty ? null : validationMessage;
            }
            else
            {
                // Compare the value to the maximum allowed by the attribute.
                return convertedMinimumValue < convertedValueFromProperty ? null : validationMessage;
            }
        }
Exemple #41
0
 public ObterProdutoQueryHandler(IValidationMessage validation, IMediator mediator, IProdutoRepository repository)
     : base(validation, mediator, repository)
 {
 }