/// <summary>
 /// Initializes a new instance of the <see cref="CommonValidationResult"/> class.
 /// </summary>
 /// <param name="rule">The rule.</param>
 /// <param name="target">The target.</param>
 /// <param name="message">The message.</param>
 /// <param name="success">if set to <c>true</c> [success].</param>
 public CommonValidationResult(IValidator rule, IValidatable target, string message, bool success)
 {
     Rule = rule;
     Target = target;
     Message = message;
     Success = success;
 }
예제 #2
0
 public ValidationResults(IValidatable target)
 {
     foreach (var result in target.Validate())
     {
         validationResults.Add(result);
     }
 }
예제 #3
0
 public void AssertInfo(bool result, IValidatable sender, string failMessage)
 {
     if (!result)
     {
         AddMessage(MyValidationLevel.INFO, failMessage, sender);
     }
 }
예제 #4
0
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="validater">验证器</param>
        public Validater AddCondition(IValidatable validater)
        {
            ValidateResult validateResult = validater.Validate();
            if (!validateResult.IsValidated)
                _ErrorMessageList.AddRange(validateResult.ErrorMessage);

            return this;
        }
예제 #5
0
 public void AssertError(bool result, IValidatable sender, string failMessage)
 {
     if (!result)
     {
         ValidationSucessfull = false;
         AddMessage(MyValidationLevel.ERROR, failMessage, sender);
     }
 }
        /// <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;
        }
        /// <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(this.ValidateIfMemberValueIsValid))
            {
                return true;
            }

            string valueToParse = string.Empty;
            bool evaluateInverseValue = false;
            if (this.ValidateIfMemberValueIsValid.StartsWith("!"))
            {
                evaluateInverseValue = true;
                valueToParse = this.ValidateIfMemberValueIsValid.Substring(1);
            }
            else
            {
                valueToParse = this.ValidateIfMemberValueIsValid;
            }

            bool result = false;
            object valueToCompare = this.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 = this.ValidationMessageType;
                numberGreaterThanRule.FailureMessage = this.FailureMessage;
                PropertyInfo property = this.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;
        }
        /// <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 (!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);

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

                if (secondaryPropertyValue != null && !(secondaryPropertyValue is string))
                {
                    int output = 0;
                    if (int.TryParse(secondaryPropertyValue.ToString(), NumberStyles.Integer, null, out output))
                    {
                        this.GreaterThanValue = output;
                    }
                }
                else if (secondaryPropertyValue != null && secondaryPropertyValue is string)
                {
                    this.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 = (this.GreaterThanValue > value.ToString().Length || value.ToString().Length == 0) ? validationMessage : null;
            }

            return this.RunInterceptedValidation(sender, property, result);
        }
예제 #9
0
        private static string HandleValidationDevalidation(string identifier, AttestationMode mode)
        {
            AuthenticationData authData = GetAuthenticationDataAndCulture();

            IValidatable validatableItem     = null;
            string       validatedTemplate   = string.Empty;
            string       devalidatedTemplate = string.Empty;

            char   costType = identifier[0];
            int    itemId   = Int32.Parse(identifier.Substring(1));
            Int64  amountCents;
            string beneficiary = string.Empty;
            string result      = string.Empty;

            // A lot of this code was copied from attest/deattest, even though validation only concerns expense receipts

            switch (costType)
            {
            case 'E':     // Expense claim
                ExpenseClaim expense = ExpenseClaim.FromIdentity(itemId);
                if (expense.OrganizationId != authData.CurrentOrganization.Identity)
                {
                    throw new InvalidOperationException("Called to attest out-of-org line item");
                }
                if (
                    !authData.CurrentUser.HasAccess(new Access(authData.CurrentOrganization,
                                                               AccessAspect.Financials,
                                                               AccessType.Write)))
                {
                    throw new UnauthorizedAccessException();
                }

                validatableItem     = expense;
                validatedTemplate   = Resources.Pages.Financial.ValidateReceipts_ReceiptsValidated;
                devalidatedTemplate = Resources.Pages.Financial.ValidateReceipts_ReceiptsDevalidated;
                amountCents         = expense.AmountCents;

                break;

            default:
                throw new InvalidOperationException("Unknown Cost Type in HandleValidationDevalidation: \"" +
                                                    identifier + "\"");
            }

            // Finally, attest or deattest

            if (mode == AttestationMode.Attestation)
            {
                validatableItem.Validate(authData.CurrentUser);
                result = string.Format(validatedTemplate, itemId, authData.CurrentOrganization.Currency.Code,
                                       amountCents / 100.0);
            }
            else if (mode == AttestationMode.Deattestation)
            {
                validatableItem.Devalidate(authData.CurrentUser);
                result = string.Format(devalidatedTemplate, itemId, authData.CurrentOrganization.Currency.Code,
                                       amountCents / 100.0);
            }
            else
            {
                throw new InvalidOperationException("Unknown Attestation Mode: " + mode);
            }

            return(result);
        }
예제 #10
0
        internal static StoreObjectValidationError[] CreateStoreObjectValiationErrorArray(IValidatable validatable, ValidationContext context)
        {
            IList <StoreObjectValidationError> list = new List <StoreObjectValidationError>();

            validatable.Validate(context, list);
            StoreObjectValidationError[] array;
            if (list.Count > 0)
            {
                array = new StoreObjectValidationError[list.Count];
                list.CopyTo(array, 0);
            }
            else
            {
                array = Validation.EmptyValidationErrorArray;
            }
            return(array);
        }
예제 #11
0
        public ChildFormArrayPageCS(IValidatable formArrayValidatable)
        {
            this.formArrayValidatable = formArrayValidatable;
            this.formsCollectionDisplayTemplateDescriptor = (FormsCollectionDisplayTemplateDescriptor)this.formArrayValidatable.GetType()
                                                            .GetProperty(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .FormsCollectionDisplayTemplate))
                                                            .GetValue(this.formArrayValidatable);

            Content = new AbsoluteLayout
            {
                HorizontalOptions = LayoutOptions.Fill,
                VerticalOptions   = LayoutOptions.Fill,
                Children          =
                {
                    new ContentView
                    {
                        Content = new StackLayout
                        {
                            Style    = LayoutHelpers.GetStaticStyleResource("FormArrayPopupViewStyle"),
                            Children =
                            {
                                new Grid
                                {
                                    Style    = LayoutHelpers.GetStaticStyleResource("PopupHeaderStyle"),
                                    Children =
                                    {
                                        new Label
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupHeaderLabelStyle"),
                                        }.AddBinding(Label.TextProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .Title)))
                                    }
                                },
                                new CollectionView
                                {
                                    Style        = LayoutHelpers.GetStaticStyleResource("FormArrayPopupCollectionViewStyle"),
                                    ItemTemplate = LayoutHelpers.GetCollectionViewItemTemplate
                                                   (
                                        this.formsCollectionDisplayTemplateDescriptor.TemplateName,
                                        this.formsCollectionDisplayTemplateDescriptor.Bindings
                                                   )
                                }
                                .AddBinding(ItemsView.ItemsSourceProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .Items)))
                                .AddBinding(SelectableItemsView.SelectionChangedCommandProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .SelectionChangedCommand)))
                                .AddBinding(SelectableItemsView.SelectedItemProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .SelectedItem))),
                                new BoxView                  {
                                    Style = LayoutHelpers.GetStaticStyleResource("PopupFooterSeparatorStyle")
                                },
                                new Grid
                                {
                                    Style             = LayoutHelpers.GetStaticStyleResource("PopupFooterStyle"),
                                    ColumnDefinitions =
                                    {
                                        new ColumnDefinition {
                                            Width = new GridLength(1, GridUnitType.Star)
                                        },
                                        new ColumnDefinition {
                                            Width = new GridLength(1, GridUnitType.Star)
                                        },
                                        new ColumnDefinition {
                                            Width = new GridLength(1, GridUnitType.Star)
                                        },
                                        new ColumnDefinition {
                                            Width = new GridLength(1, GridUnitType.Star)
                                        },
                                        new ColumnDefinition {
                                            Width = new GridLength(1, GridUnitType.Star)
                                        }
                                    },
                                    Children =
                                    {
                                        new Button
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupAddButtonStyle")
                                        }
                                        .AddBinding(Button.CommandProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .AddCommand))),
                                        new Button
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupEditButtonStyle")
                                        }
                                        .AddBinding(Button.CommandProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .EditCommand)))
                                        .SetGridColumn(1),
                                        new Button
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupDeleteButtonStyle")
                                        }
                                        .AddBinding(Button.CommandProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .DeleteCommand)))
                                        .SetGridColumn(2),
                                        new Button
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupCancelButtonStyle")
                                        }
                                        .AddBinding(Button.CommandProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .CancelCommand)))
                                        .SetGridColumn(3),
                                        new Button
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupAcceptButtonStyle")
                                        }
                                        .AddBinding(Button.CommandProperty, new Binding(nameof(FormArrayValidatableObject <ObservableCollection <string>, string> .SubmitCommand)))
                                        .SetGridColumn(4)
                                    }
                                }
                            }
                        }
                    }
                    .AssignDynamicResource(VisualElement.BackgroundColorProperty, "PopupViewBackgroundColor")
                    .SetAbsoluteLayoutBounds(new Rectangle(0, 0, 1, 1))
                    .SetAbsoluteLayoutFlags(AbsoluteLayoutFlags.All)
                }
            };

            this.BackgroundColor = Color.Transparent;
            Visual = VisualMarker.Material;
            this.BindingContext = this.formArrayValidatable;
        }
예제 #12
0
        public void ValidateMustNotThrowIfSettingsAreCorrect(IValidatable settings)
        {
            Action action = () => settings.Validate();

            action.Should().NotThrow();
        }
예제 #13
0
 /// <summary>
 /// Gets the validation message.
 /// </summary>
 public static string ValidationMessage(this IValidatable input)
 {
     return(input.ValidationResult().Message);
 }
예제 #14
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 abstract IValidationMessage Validate(PropertyInfo property, IValidatable sender);
예제 #15
0
 public static bool IsValid(this IValidatable validatableObject)
 {
     validatableObject.ThrowIfNull(nameof(validatableObject));
     return(validatableObject.IsValid(out ValidationCollection _));
 }
예제 #16
0
        private void AddMessage(MyValidationLevel level, string message, IValidatable sender)
        {
            string[] lines = message.Split('\n');

            Messages.Add(new MyValidationMessage(level, lines[0], sender));

            for (int i = 1; i < lines.Length; i++)
            {
                Messages.Add(new MyValidationMessage(level, lines[i], null));
            }
        }
        private void UpdateValidatables(IEnumerable <IValidatable> properties, object source, List <FormItemSettingsDescriptor> fieldSettings, string parentField = null)
        {
            IDictionary <string, object>       existingValues       = mapper.Map <Dictionary <string, object> >(source) ?? new Dictionary <string, object>();
            IDictionary <string, IValidatable> propertiesDictionary = properties.ToDictionary(p => p.Name);

            foreach (var setting in fieldSettings)
            {
                if (setting is MultiSelectFormControlSettingsDescriptor multiSelectFormControlSetting)
                {
                    if (existingValues.TryGetValue(multiSelectFormControlSetting.Field, out object @value) && @value != null)
                    {
                        IValidatable multiSelectValidatable = propertiesDictionary[GetFieldName(multiSelectFormControlSetting.Field)];

                        if (!multiSelectValidatable.Type.GetUnderlyingElementType().AssignableFrom(@value.GetType().GetUnderlyingElementType()))
                        {
                            throw new ArgumentException($"{nameof(multiSelectFormControlSetting)}: 74B8794A-9C00-4A25-8089-10957DF0A5EC");
                        }

                        multiSelectValidatable.Value = Activator.CreateInstance
                                                       (
                            multiSelectValidatable.Type,
                            new object[] { @value }
                                                       );
                    }
                }
                else if (setting is FormControlSettingsDescriptor controlSetting)
                {//must stay after MultiSelect because MultiSelect extends FormControl
                    if (existingValues.TryGetValue(controlSetting.Field, out object @value) && @value != null)
                    {
                        if (!propertiesDictionary[GetFieldName(controlSetting.Field)].Type.AssignableFrom(@value.GetType()))
                        {
                            throw new ArgumentException($"{nameof(controlSetting)}: F4B014E4-B04C-455D-8AE5-1F2551BEC190");
                        }

                        propertiesDictionary[GetFieldName(controlSetting.Field)].Value = @value;
                    }
                }
                else if (setting is FormGroupSettingsDescriptor formGroupSetting)
                {
                    if (existingValues.TryGetValue(formGroupSetting.Field, out object @value) && @value != null)
                    {
                        if (formGroupSetting.FormGroupTemplate == null)
                        {
                            throw new ArgumentException($"{nameof(formGroupSetting.FormGroupTemplate)}: 74E0697E-B5EF-4939-B0B4-8B7E4AE5544B");
                        }

                        if (formGroupSetting.FormGroupTemplate.TemplateName == FromGroupTemplateNames.InlineFormGroupTemplate)
                        {
                            UpdateValidatables(properties, @value, formGroupSetting.FieldSettings, GetFieldName(formGroupSetting.Field));
                        }
                        else if (formGroupSetting.FormGroupTemplate.TemplateName == FromGroupTemplateNames.PopupFormGroupTemplate)
                        {
                            if (!propertiesDictionary[GetFieldName(formGroupSetting.Field)].Type.AssignableFrom(@value.GetType()))
                            {
                                throw new ArgumentException($"{nameof(formGroupSetting)}: 83ADA1B9-5951-4643-BE40-E9BB6DB45C06");
                            }

                            propertiesDictionary[GetFieldName(formGroupSetting.Field)].Value = @value;
                        }
                        else
                        {
                            throw new ArgumentException($"{nameof(formGroupSetting.FormGroupTemplate.TemplateName)}: 5504FE49-2766-4D7C-916D-8FC633477DB1");
                        }
                    }
                }
                else if (setting is FormGroupArraySettingsDescriptor formGroupArraySetting)
                {
                    if (existingValues.TryGetValue(formGroupArraySetting.Field, out object @value) && @value != null)
                    {
                        IValidatable forArrayValidatable = propertiesDictionary[GetFieldName(formGroupArraySetting.Field)];

                        if (!forArrayValidatable.Type.GetUnderlyingElementType().AssignableFrom(@value.GetType().GetUnderlyingElementType()))
                        {
                            throw new ArgumentException($"{nameof(multiSelectFormControlSetting)}: CCB454D1-8119-475B-9A2B-1EB10E513959");
                        }

                        forArrayValidatable.Value = Activator.CreateInstance
                                                    (
                            forArrayValidatable.Type,
                            new object[] { @value }
                                                    );
                    }
                }
                else if (setting is FormGroupBoxSettingsDescriptor groupBoxSettingsDescriptor)
                {
                    UpdateValidatables(properties, source, groupBoxSettingsDescriptor.FieldSettings, parentField);
                }
            }

            string GetFieldName(string field)
            => string.IsNullOrEmpty(parentField)
                    ? field
                    : $"{parentField}.{field}";
        }
예제 #18
0
 protected override void Context()
 {
     _validatableObject = A.Fake <IValidatable>();
     _businessRuleSet   = A.Fake <IBusinessRuleSet>();
     A.CallTo(() => _validatableObject.Rules).Returns(_businessRuleSet);
 }
예제 #19
0
 public bool Remove(IValidatable obj) => list.Remove(obj);
예제 #20
0
 public void Add(IValidatable obj) => list.Add(obj);
예제 #21
0
        public ChildFormPageCS(IValidatable formValidatable)
        {
            this.formValidatable             = formValidatable;
            this.formGroupSettingsDescriptor = (FormGroupSettingsDescriptor)this.formValidatable.GetType()
                                               .GetProperty(nameof(FormValidatableObject <object> .FormSettings))
                                               .GetValue(this.formValidatable);

            Content = new AbsoluteLayout
            {
                HorizontalOptions = LayoutOptions.Fill,
                VerticalOptions   = LayoutOptions.Fill,
                Children          =
                {
                    new ContentView
                    {
                        Content = new StackLayout
                        {
                            Style    = LayoutHelpers.GetStaticStyleResource("ChildFormPopupViewStyle"),
                            Children =
                            {
                                new Grid
                                {
                                    Style    = LayoutHelpers.GetStaticStyleResource("PopupHeaderStyle"),
                                    Children =
                                    {
                                        new Label
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupHeaderLabelStyle"),
                                        }.AddBinding(Label.TextProperty, new Binding("Title"))
                                    }
                                },
                                new CollectionView
                                {
                                    Style        = LayoutHelpers.GetStaticStyleResource("ChildFormPopupCollectionViewStyle"),
                                    ItemTemplate = EditFormViewHelpers.QuestionTemplateSelector
                                }
                                .AddBinding(ItemsView.ItemsSourceProperty, new Binding("Properties")),
                                new BoxView                  {
                                    Style = LayoutHelpers.GetStaticStyleResource("PopupFooterSeparatorStyle")
                                },
                                new Grid
                                {
                                    Style             = LayoutHelpers.GetStaticStyleResource("PopupFooterStyle"),
                                    ColumnDefinitions =
                                    {
                                        new ColumnDefinition {
                                            Width = new GridLength(1, GridUnitType.Star)
                                        },
                                        new ColumnDefinition {
                                            Width = new GridLength(1, GridUnitType.Star)
                                        },
                                        new ColumnDefinition {
                                            Width = new GridLength(1, GridUnitType.Star)
                                        }
                                    },
                                    Children =
                                    {
                                        new Button
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupCancelButtonStyle")
                                        }
                                        .AddBinding(Button.CommandProperty, new Binding("CancelCommand"))
                                        .SetGridColumn(1),
                                        new Button
                                        {
                                            Style = LayoutHelpers.GetStaticStyleResource("PopupAcceptButtonStyle")
                                        }
                                        .AddBinding(Button.CommandProperty, new Binding("SubmitCommand"))
                                        .SetGridColumn(2)
                                    }
                                }
                            }
                        }
                    }
                    .AssignDynamicResource(VisualElement.BackgroundColorProperty, "PopupViewBackgroundColor")
                    .SetAbsoluteLayoutBounds(new Rectangle(0, 0, 1, 1))
                    .SetAbsoluteLayoutFlags(AbsoluteLayoutFlags.All)
                }
            };

            this.BackgroundColor = Color.Transparent;
            this.BindingContext  = this.formValidatable;
        }
예제 #22
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));
        }
예제 #23
0
 protected override void OnInitialized()
 {
     base.OnInitialized();
     IValidatable.Configure(this, out _computedColor, out _hasError, out _hasSuccess, out _hasState,
                            out _shouldValidate, out _validationState, out _validationMessages, out _hasMessages).DisposeWith(_disposables);
 }
예제 #24
0
 /// <summary>
 /// Gets the <see cref="ValidationResult"/> object.
 /// </summary>
 public static ValidationResult ValidationResult(this IValidatable input)
 {
     // This avoids needing a null check in our code when we validate nullable objects
     return(input == null ? new ValidationResult(false, "Cannot validate null.") : input.Validate());
 }
예제 #25
0
 public PMConfigValidator(IValidatable parent) : base(parent)
 {
 }
예제 #26
0
 public void AddInfo(IValidatable sender, string message)
 {
     AssertInfo(false, sender, message);
 }
 /// <summary>
 /// Gets the status by testing the supplied value.
 /// </summary>
 /// <returns>The status of the supplied value.</returns>
 /// <param name="provider">Object on which the field exists.</param>
 /// <param name="testValue">Test value.</param>
 private ValidationStatus GetStatus(Object provider, IValidatable testValue)
 {
     return(this.Attribute.ValidationMethod == null?
            testValue.GetValidationStatus(out m_CurrentStatusTooltip) :
                this.Attribute.ValidationMethod(provider, testValue, out m_CurrentStatusTooltip));
 }
예제 #28
0
        /// <summary>
        /// Gets the validation context of the specified model.
        /// </summary>
        /// <param name="validatable">The model.</param>
        /// <returns>The validation context.</returns>
        public static IValidationContext GetValidationContext(this IValidatable validatable)
        {
            Argument.IsNotNull("model", validatable);

            return(validatable.ValidationContext);
        }
예제 #29
0
 public IValidator CreateValidator(IValidatable item)
 {
     return(new BlankValidator(item));
 }
 protected override void Context()
 {
     _objectToValidate = A.Fake <IValidatable>();
     _rules            = A.Fake <IBusinessRuleSet>();
     A.CallTo(() => _objectToValidate.Rules).Returns(_rules);
 }
예제 #31
0
 public bool IsNeedValidate(IValidatable item)
 {
     return(true);
 }
예제 #32
0
 /// <summary>
 /// Converts the error dictionary to a string
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 protected string getObjectErrors(IValidatable obj)
 {
     return(DictionaryHelper.ToString(obj.Errors));
 }
예제 #33
0
        public bool Validate(IValidatable sender, string fieldName, object value)
        {
            IFieldValidator constraint = Constraints[fieldName];
            if (constraint == null) { return true; }//nothing to validate, pass
            string message;
            if (constraint.Level == ErrorLevel.Error)
            {
                message = constraint.ErrorMessage;
            }
            else if (constraint.Level == ErrorLevel.Warning)
            {
                message = "Warning::" + constraint.ErrorMessage;
            }
            else
            {
                message = String.Empty;
            }
            if (constraint.Validate(sender, value) == false)//fail validation
            {

                sender.AddError(fieldName, message);
                return false;
            }
            else //passes validation
            {
                sender.RemoveError(fieldName, message);
                return true;
            }
        }
예제 #34
0
 private static ValidState validateIValidatable(Doc self, ObjectGraph graph, IValidatable validatable, ValidState state, string scope)
 => !graph.Visited(validatable) ? validatable.Validate(state, scope) : state;
예제 #35
0
 public void AssertIsValid(IValidatable obj)
 {
     Assert.That(obj.IsValid(), Is.True);
     Assert.That(obj.ValidationResults(), Has.Count.EqualTo(0));
 }
예제 #36
0
 public static bool IsValid(this IValidatable obj, ValidationContext validationContext = null)
 {
     return(!obj.Validate(validationContext).Any());
 }
 /// <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 abstract IValidationMessage Validate(PropertyInfo property, IValidatable sender);
        public List <ValidateIf <TModel> > GetConditions()
        {
            IDictionary <string, IValidatable> propertiesDictionary = properties.ToDictionary(p => p.Name);

            List <ValidateIf <TModel> > conditions = formGroupSettings.ConditionalDirectives?.Aggregate(parentList ?? new List <ValidateIf <TModel> >(), (list, kvp) =>
            {
                kvp.Value.ForEach
                (
                    descriptor =>
                {
                    if (descriptor.Definition.ClassName != nameof(ValidateIf <TModel>))
                    {
                        return;
                    }

                    const string validationsToWatchKey = "validationsToWatch";
                    if (!descriptor.Definition.Arguments.TryGetValue(validationsToWatchKey, out DirectiveArgumentDescriptor validationsToWatchDescriptor))
                    {
                        throw new ArgumentException($"{validationsToWatchKey}: A5B39033-62C9-4B5D-A800-754054169502");
                    }
                    if (!typeof(IEnumerable <string>).IsAssignableFrom(validationsToWatchDescriptor.Value.GetType()))
                    {
                        throw new ArgumentException($"{validationsToWatchDescriptor}: 60E64249-A275-4992-8444-9DC85DF108B9");
                    }

                    HashSet <string> validationsToWatch = new HashSet <string>((IEnumerable <string>)validationsToWatchDescriptor.Value);

                    IValidatable validatable = propertiesDictionary[GetFieldName(kvp.Key)];

                    validatable.Validations.ForEach
                    (
                        validationRule =>
                    {
                        if (validationsToWatch.Contains(validationRule.ClassName) == false)
                        {
                            return;
                        }

                        list.Add
                        (
                            new ValidateIf <TModel>
                        {
                            Field       = GetFieldName(kvp.Key),
                            ParentField = this.parentName,
                            Validator   = validationRule,
                            Evaluator   = (Expression <Func <TModel, bool> >)mapper.Map <FilterLambdaOperator>
                                          (
                                descriptor.Condition,
                                opts => opts.Items[PARAMETERS_KEY] = new Dictionary <string, ParameterExpression>()
                                          ).Build(),
                            DirectiveDefinition = descriptor.Definition
                        }
                        );
                    }
                    );
                }
                );

                return(list);
            }) ?? new List <ValidateIf <TModel> >();

            formGroupSettings.FieldSettings.ForEach(AddConditions);

            return(conditions);

            void AddConditions(FormItemSettingsDescriptor descriptor)
            {
                if (descriptor is FormGroupBoxSettingsDescriptor groupBox)
                {
                    groupBox.FieldSettings.ForEach(AddConditions);
                    return;
                }

                if (!(descriptor is FormGroupSettingsDescriptor childForm))
                {
                    return;
                }

                if ((childForm.FormGroupTemplate?.TemplateName) != FromGroupTemplateNames.InlineFormGroupTemplate)
                {
                    return;
                }

                conditions = new ValidateIfConditionalDirectiveHelper <TModel>
                             (
                    childForm,
                    properties,
                    mapper,
                    conditions,
                    GetFieldName(childForm.Field)
                             ).GetConditions();
            }
        }
예제 #39
0
        public const string PositiveNumberValidationMethodName = "PositiveNumber"; //Положительные числа > 0

        public UniversalCustomExpandoObjectValidator(IValidatable parent)
            : base(parent)
        {
            ValidationMethods = new Dictionary <string, ObjectValid[]>();
        }
예제 #40
0
 public void AssertIsInvalid(IValidatable obj, int expectedErrorCount)
 {
     Assert.That(obj.IsValid(), Is.False);
     Assert.That(obj.ValidationResults(), Has.Count.EqualTo(expectedErrorCount));
 }
예제 #41
0
        public static void Valid(IValidatable target, string parameterName, Func <string> message)
        {
            NotNull(target, parameterName);

            target.Validate(message);
        }
예제 #42
0
 public void AssertValidationResult(IValidatable obj, string expectedName, string expectedMessage)
 {
     AssertValidationResult(obj.ValidationResults(), expectedName, expectedMessage);
 }
        /// <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;

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

            // Ensure the property value is the same data type we are comparing to.
            if (!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,
                    numberDataType.ToString());
                throw new ArgumentNullException(error);
            }

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

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

            IValidationMessage result = null;

            if (numberDataType == ValidationNumberDataTypes.Short)
            {
                result = ValidateMinimumShortValue(propertyValue, alternateProperty, validationMessage);
            }
            else if (numberDataType == ValidationNumberDataTypes.Int)
            {
                result = ValidateMinimumIntegerValue(propertyValue, alternateProperty, validationMessage);
            }
            else if (numberDataType == ValidationNumberDataTypes.Long)
            {
                result = ValidateMinimumLongValue(propertyValue, alternateProperty, validationMessage);
            }
            else if (numberDataType == ValidationNumberDataTypes.Float)
            {
                result = ValidateMinimumFloatValue(propertyValue, alternateProperty, validationMessage);
            }
            else if (numberDataType == ValidationNumberDataTypes.Double)
            {
                result = ValidateMinimumDoubleValue(propertyValue, alternateProperty, validationMessage);
            }
            else if (numberDataType == ValidationNumberDataTypes.Decimal)
            {
                result = ValidateMinimumDecimalValue(propertyValue, alternateProperty, validationMessage);
            }

            return(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);
        }
예제 #45
0
 public ValidationResult(IValidatable source)
 {
     Source = source;
     IsValid = true;
     _Items = new List<ValidationItem>();
 }
예제 #46
0
파일: TodoTest.cs 프로젝트: gkeary/myGetOrg
 private bool IsValid(IValidatable toValidate)
 {
     ModelStateDictionary state = new ModelStateDictionary();
       toValidate.Validate(state);
       return state.IsValid;
 }
예제 #47
0
 public void AssertWarning(bool result, IValidatable sender, string failMessage)
 {
     if (!result)
     {
         AddMessage(MyValidationLevel.WARNING, failMessage, sender);
     }
 }
예제 #48
0
 public void AddError(IValidatable sender, string message)
 {
     AssertError(false, sender, message);
 }
예제 #49
0
 protected Exception CreateException(IValidatable entity)
 {
     return new Exception(entity.ValidationMessage());
 }
예제 #50
0
 public void AddWarning(IValidatable sender, string message)
 {
     AssertWarning(false, sender, message);
 }
예제 #51
0
 internal MyValidationMessage(MyValidationLevel level, string message, IValidatable sender)
 {
     Level = level;
     Message = message;
     Sender = sender;
 }
 /// <summary>
 /// Call the Validate() method for <paramref name="value"/>
 /// </summary>
 public static void IsValidated(IValidatable value, string propertyPath, string propertyName, string errorLocation, string customMessage = null)
 {
     value?.Validate(errorLocation, $"{propertyPath}.{propertyName}");
 }
예제 #53
0
        /// <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>
        /// 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);
        }
예제 #55
0
 protected void CheckValidity(IValidatable entity)
 {
     if (!entity.isValid()) {
         throw CreateException(entity);
     }
 }