コード例 #1
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            ValidationErrorCollection validationErrors = base.Validate(manager, obj);
            DependencyObject          dependencyObject = obj as DependencyObject;

            if (dependencyObject == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(DependencyObject).FullName), "obj");
            }

            ArrayList allProperties = new ArrayList();

            // Validate all the settable dependency properties
            // attached property can not be found through the call to DependencyProperty.FromType()
            foreach (DependencyProperty prop in DependencyProperty.FromType(dependencyObject.GetType()))
            {
                // This property is attached to some other object.  We should not validate it here
                // because the context is wrong.
                if (!prop.IsAttached)
                {
                    allProperties.Add(prop);
                }
            }
            //


            foreach (DependencyProperty prop in dependencyObject.MetaDependencyProperties)
            {
                if (prop.IsAttached)
                {
                    if (obj.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance) == null)
                    {
                        allProperties.Add(prop);
                    }
                }
            }

            foreach (DependencyProperty prop in allProperties)
            {
                object[]         validationVisibilityAtrributes = prop.DefaultMetadata.GetAttributes(typeof(ValidationOptionAttribute));
                ValidationOption validationVisibility           = (validationVisibilityAtrributes.Length > 0) ? ((ValidationOptionAttribute)validationVisibilityAtrributes[0]).ValidationOption : ValidationOption.Optional;
                if (validationVisibility != ValidationOption.None)
                {
                    validationErrors.AddRange(ValidateDependencyProperty(dependencyObject, prop, manager));
                }
            }

            return(validationErrors);
        }
コード例 #2
0
        /// <summary>
        /// Renders an input tag for the specified model element
        /// </summary>
        /// <typeparam name="TProperty">Property type of the element</typeparam>
        /// <param name="expression">Property expression</param>
        /// <param name="inputTagType">Type of the input tag</param>
        /// <param name="autoFocus">Autofocus type</param>
        /// <param name="validationOption">Validation type</param>
        public MvcHtmlString InputFor <TProperty>(
            Expression <Func <TModel, TProperty> > expression,
            InputTagType inputTagType         = InputTagType.Text,
            AutoFocus autoFocus               = AutoFocus.None,
            ValidationOption validationOption = ValidationOption.Always)
        {
            var modelMetadata = ModelMetadata.FromLambdaExpression(expression, HtmlHelper.ViewData);

            return(_form.IsHorizontal
                ? _buildHelper.BuildHorizontalInput(modelMetadata, inputTagType, autoFocus, validationOption)
                : _buildHelper.BuildColumnarInput(modelMetadata, inputTagType, autoFocus, validationOption));
        }
コード例 #3
0
ファイル: SpecialCharacters.cs プロジェクト: kehinze/Hermes
        public bool IsValid(string expression, ValidationOption validationOption)
        {
            Mandate.ParameterNotNullOrEmpty(expression, "expression");

            ValidateSpecialCharacterFormat(expression);

            IEnumerable<char> specialCharacters = expression.ToCharArray();

            specialCharacters = validationOption == ValidationOption.AllowLetters
                ? specialCharacters.Where(c => !Char.IsLetterOrDigit(c))
                : specialCharacters.Where(c => !Char.IsDigit(c));

            return specialCharacters.All(specialCharacter => allowedSpecialCharacters.Contains(specialCharacter));
        }
コード例 #4
0
ファイル: Validator.cs プロジェクト: dox0/DotNet471RS3
        public virtual ValidationErrorCollection ValidateProperties(ValidationManager manager, object obj)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            ValidationErrorCollection errors = new ValidationErrorCollection();

            Activity activity = manager.Context[typeof(Activity)] as Activity;

            // Validate all members that support validations.
            Walker walker = new Walker(true);

            walker.FoundProperty += delegate(Walker w, WalkerEventArgs args)
            {
                //If we find dynamic property of the same name then we do not invoke the validator associated with the property
                //Attached dependency properties will not be found by FromName().

                // args.CurrentProperty can be null if the property is of type IList.  The walker would go into each item in the
                // list, but we don't need to validate these items.
                if (args.CurrentProperty != null)
                {
                    DependencyProperty dependencyProperty = DependencyProperty.FromName(args.CurrentProperty.Name, args.CurrentProperty.DeclaringType);
                    if (dependencyProperty == null)
                    {
                        object[]         validationVisibilityAtrributes = args.CurrentProperty.GetCustomAttributes(typeof(ValidationOptionAttribute), true);
                        ValidationOption validationVisibility           = (validationVisibilityAtrributes.Length > 0) ? ((ValidationOptionAttribute)validationVisibilityAtrributes[0]).ValidationOption : ValidationOption.Optional;
                        if (validationVisibility != ValidationOption.None)
                        {
                            errors.AddRange(ValidateProperty(args.CurrentProperty, args.CurrentPropertyOwner, args.CurrentValue, manager));
                            // don't probe into subproperties as validate object inside the ValidateProperties call does it for us
                            args.Action = WalkerAction.Skip;
                        }
                    }
                }
            };

            walker.WalkProperties(activity, obj);

            return(errors);
        }
コード例 #5
0
ファイル: Validator.cs プロジェクト: dox0/DotNet471RS3
        internal protected ValidationErrorCollection ValidateProperty(PropertyInfo propertyInfo, object propertyOwner, object propertyValue, ValidationManager manager)
        {
            ValidationErrorCollection errors = new ValidationErrorCollection();

            object[]                  validationVisibilityAtrributes = propertyInfo.GetCustomAttributes(typeof(ValidationOptionAttribute), true);
            ValidationOption          validationVisibility           = (validationVisibilityAtrributes.Length > 0) ? ((ValidationOptionAttribute)validationVisibilityAtrributes[0]).ValidationOption : ValidationOption.Optional;
            PropertyValidationContext propertyValidationContext      = new PropertyValidationContext(propertyOwner, propertyInfo, propertyInfo.Name);

            manager.Context.Push(propertyValidationContext);

            try
            {
                if (propertyValue != null)
                {
                    errors.AddRange(ValidationHelpers.ValidateObject(manager, propertyValue));
                    if (propertyValue is IList)
                    {
                        PropertyValidationContext childContext = new PropertyValidationContext(propertyValue, null, "");
                        manager.Context.Push(childContext);

                        try
                        {
                            foreach (object child in (IList)propertyValue)
                            {
                                errors.AddRange(ValidationHelpers.ValidateObject(manager, child));
                            }
                        }
                        finally
                        {
                            System.Diagnostics.Debug.Assert(manager.Context.Current == childContext, "Unwinding contextStack: the item that is about to be popped is not the one we pushed.");
                            manager.Context.Pop();
                        }
                    }
                }
            }
            finally
            {
                System.Diagnostics.Debug.Assert(manager.Context.Current == propertyValidationContext, "Unwinding contextStack: the item that is about to be popped is not the one we pushed.");
                manager.Context.Pop();
            }

            return(errors);
        }
コード例 #6
0
 protected internal ValidationErrorCollection ValidateProperty(PropertyInfo propertyInfo, object propertyOwner, object propertyValue, ValidationManager manager)
 {
     ValidationErrorCollection errors = new ValidationErrorCollection();
     object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(ValidationOptionAttribute), true);
     if (customAttributes.Length > 0)
     {
         ValidationOption validationOption = ((ValidationOptionAttribute) customAttributes[0]).ValidationOption;
     }
     PropertyValidationContext context = new PropertyValidationContext(propertyOwner, propertyInfo, propertyInfo.Name);
     manager.Context.Push(context);
     try
     {
         if (propertyValue == null)
         {
             return errors;
         }
         errors.AddRange(ValidationHelpers.ValidateObject(manager, propertyValue));
         if (!(propertyValue is IList))
         {
             return errors;
         }
         PropertyValidationContext context2 = new PropertyValidationContext(propertyValue, null, "");
         manager.Context.Push(context2);
         try
         {
             foreach (object obj2 in (IList) propertyValue)
             {
                 errors.AddRange(ValidationHelpers.ValidateObject(manager, obj2));
             }
             return errors;
         }
         finally
         {
             manager.Context.Pop();
         }
     }
     finally
     {
         manager.Context.Pop();
     }
     return errors;
 }
コード例 #7
0
ファイル: SpecialCharacters.cs プロジェクト: kehinze/Hermes
 public void Validate(string expression, ValidationOption validationOption)
 {
     if (!IsValid(expression, validationOption))
     {
         throw new CronException(ErrorMessages.InvalidCharacterError);
     }
 }
コード例 #8
0
        /// <summary>
        /// 拒绝
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <param name="message">错误信息</param>
        /// <param name="option">结果选项</param>
        public ValidationFailure Reject <T>(Expression <Func <T, object> > expression, string message, ValidationOption option) where T : AggregateRoot
        {
            var model = expression as ParameterExpression;

            if (model != null)
            {
                return(new ValidationFailure()
                {
                    ErrorMessage = message, MemberName = model.Name, Option = option
                });
            }

            var member = expression as MemberExpression;

            if (member != null && member.Member != null)
            {
                return(new ValidationFailure()
                {
                    ErrorMessage = message, MemberName = member.Member.Name, Option = option
                });
            }

            var unary = expression as UnaryExpression;

            if (unary != null)
            {
                var property = unary.Operand as MemberExpression;
                if (property != null)
                {
                    return(new ValidationFailure()
                    {
                        ErrorMessage = message, MemberName = property.Member.Name, Option = option
                    });
                }
            }

            return(new ValidationFailure()
            {
                ErrorMessage = message, MemberName = expression.ToString(), Option = option
            });
        }
コード例 #9
0
        /// <summary>
        /// Builds a horizontal input control
        /// </summary>
        /// <param name="modelMetadata">Model metadata</param>
        /// <param name="inputTagType">Type of the input tag</param>
        /// <param name="autoFocus">Autofocus type</param>
        /// <param name="validationOption">Validation type</param>
        public MvcHtmlString BuildHorizontalInput(ModelMetadata modelMetadata, InputTagType inputTagType,
                                                  AutoFocus autoFocus, ValidationOption validationOption)
        {
            // --- The form group that encapsulates the label and the control
            var propName  = CamelCase(modelMetadata.PropertyName);
            var formGroup = new BsFormGroup {
                Depth = _formBuilder.Depth + 1
            };
            var condition = string.Format("{0}{1}",
                                          "{0}.{1}.$invalid",
                                          validationOption == ValidationOption.WhenDirty ? " && {0}.{1}.$dirty" : "");

            formGroup.Attr(NgTag.NgClass, string.Format("{{'has-error': " + condition + ", 'has-feedback': " + condition + "}}",
                                                        _formBuilder.BsForm.FormName, propName));

            if (inputTagType == InputTagType.Text)
            {
                var label    = CreateTextLabel(modelMetadata);
                var inputDiv = new BsHtmlElement(HtmlTag.Div);
                inputDiv.ApplyColumnWidths(null,
                                           _formBuilder.BsForm.InputWidthXs,
                                           _formBuilder.BsForm.InputWidthSm,
                                           _formBuilder.BsForm.InputWidthMd,
                                           _formBuilder.BsForm.InputWidthLg);
                var input = CreateInput(inputTagType, autoFocus, modelMetadata, propName);

                // --- Assemble the elements
                formGroup.AddChild(label).AddChild(inputDiv);
                inputDiv.AddChild(input);

                // --- Add optional help text
                if (!string.IsNullOrEmpty(modelMetadata.Description))
                {
                    var helpText = new BsHtmlElement(HtmlTag.Span);
                    helpText.CssClass(BsClass.Control.Help);
                    helpText.AddChild(new HtmlText(modelMetadata.Description));
                    inputDiv.AddChild(helpText);
                }

                // --- Create validation tags
                AddValidationTags(inputDiv, modelMetadata, validationOption);
            }
            else if (inputTagType == InputTagType.CheckBox)
            {
                var sizingDiv = new BsHtmlElement(HtmlTag.Div);
                sizingDiv.ApplyColumnWidths(null,
                                            _formBuilder.BsForm.InputWidthXs,
                                            _formBuilder.BsForm.InputWidthSm,
                                            _formBuilder.BsForm.InputWidthMd,
                                            _formBuilder.BsForm.InputWidthLg);
                sizingDiv.ApplyColumnOffsets(null,
                                             _formBuilder.BsForm.LabelWidthXs,
                                             _formBuilder.BsForm.LabelWidthSm,
                                             _formBuilder.BsForm.LabelWidthMd,
                                             _formBuilder.BsForm.LabelWidthLg);

                var checkBoxDiv = new BsHtmlElement(HtmlTag.Div).CssClass(BsClass.Control.CheckBox);
                var label       = new BsHtmlElement(HtmlTag.Label);
                var input       = CreateInput(inputTagType, autoFocus, modelMetadata, propName);
                input.Attr(modelMetadata.Model != null && modelMetadata.Model.ToString().ToLower() == "true",
                           HtmlAttr.Checked, HtmlAttr.Checked);
                var hiddenInput = new BsHtmlElement(HtmlTag.Input)
                                  .Attr(HtmlAttr.Name, modelMetadata.PropertyName)
                                  .Attr(HtmlAttr.Type, HtmlInputType.Hidden)
                                  .Attr(HtmlAttr.Value, "false");

                // --- Assemble the elements
                formGroup.AddChild(sizingDiv);
                sizingDiv.AddChild(checkBoxDiv);
                checkBoxDiv.AddChild(label);
                label
                .AddChild(input)
                .AddChild(new HtmlText(modelMetadata.DisplayName ?? modelMetadata.PropertyName))
                .AddChild(hiddenInput);
            }
            return(formGroup.Markup);
        }
コード例 #10
0
 /// <summary>
 /// Renders validation tags
 /// </summary>
 /// <param name="container">Container to hold validation tags</param>
 /// <param name="modelMetadata">Model metadata</param>
 /// <param name="validationOption">Validation mode</param>
 private void AddValidationTags(HtmlElementBase <BsHtmlElement> container, ModelMetadata modelMetadata, ValidationOption validationOption)
 {
     foreach (var key in modelMetadata.AdditionalValues.Keys)
     {
         var attr = modelMetadata.AdditionalValues[key] as ValidationAttributeMetadata;
         if (attr == null)
         {
             continue;
         }
         var valTag = new HtmlElement("span")
                      .CssClass(BsClass.GlyphFa.ExclamationCircle)
                      .CssClass(BsClass.Control.Feedback)
                      .Attr(HtmlAttr.Style, "cursor: default;")
                      .Attr(BsClass.Control.Toggle, "errorhint")
                      .Attr(NgTag.NgShow, string.Format(
                                validationOption == ValidationOption.Always
                     ? "{0}.{1}.$error.{2}"
                     : "{0}.{1}.$error.{2} && {0}.{1}.$dirty",
                                _formBuilder.BsForm.FormName, CamelCase(modelMetadata.PropertyName), key))
                      .Attr(BsTag.Tooltip, string.Format(attr.ErrorMessage, modelMetadata.DisplayName))
                      .Attr(BsTag.TooltipAppendToBody, "true")
                      .Attr(BsTag.TooltipPlacement, "left");
         container.AddChild(valTag);
     }
 }
コード例 #11
0
 /// <summary>
 /// Builds a columnar input control
 /// </summary>
 /// <param name="modelMetadata">Model metadata</param>
 /// <param name="inputTagType">Type of the input tag</param>
 /// <param name="autoFocus">Autofocus type</param>
 /// <param name="validationOption">Validation type</param>
 public MvcHtmlString BuildColumnarInput(ModelMetadata modelMetadata, InputTagType inputTagType,
                                         AutoFocus autoFocus, ValidationOption validationOption)
 {
     return(MvcHtmlString.Empty);
 }
コード例 #12
0
        /// <summary>
        /// 前台注入
        /// </summary>
        /// <param name="pageKey"></param>
        /// <param name="itemList"></param>
        public static void Init(string pageKey, params OptionItem[] itemList)
        {
            ValidationOption option    = new ValidationOption();
            string           uk        = Guid.NewGuid().ToString().Replace("-", "");//唯一函数名
            string           script    = string.Empty;
            StringBuilder    itemsCode = new StringBuilder();

            foreach (var item in itemList)
            {
                //为script添加name方便动态删除
                script = @"<script name=""scriptValidates"">
var bindValidation{1}=function(name,params,i,validateSize){{
     var selectorObj=$(""[name='""+name+""']"").last();
   if(params.tip!=null)
     selectorObj.attr(""tip""+i,params.tip);
     if(params.pattern!=null)
     selectorObj.attr(""pattern""+i,params.pattern);
     if(params.placeholder!=null)
     selectorObj.attr(""placeholder"",params.placeholder);
     if(params.isRequired==true)
     selectorObj.attr(""required"",params.isRequired);
     selectorObj.attr(""validatesize"",validateSize);
}}
{0}</script>";
                foreach (var itit in item.TypeParams)
                {
                    int index = item.TypeParams.IndexOf(itit);
                    switch (itit.Type)
                    {
                    case OptionItemType.Mail:
                        itit.Pattern = @"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
                        break;

                    case OptionItemType.Int:
                        itit.Pattern = @"^\\d{1,11}$";
                        break;

                    case OptionItemType.Double:
                        itit.Pattern = @"^\\d{1,11}$";
                        break;

                    case OptionItemType.IdCard:
                        itit.Pattern = @"^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$";
                        break;

                    case OptionItemType.Date:
                        itit.Pattern = @"^(((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/])(10|12|0?[13578])([-\\/])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/])(11|0?[469])([-\\/])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/])(0?2)([-\\/])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\\/])(0?2)([-\\/])(29)$)|(^([3579][26]00)([-\\/])(0?2)([-\\/])(29)$)|(^([1][89][0][48])([-\\/])(0?2)([-\\/])(29)$)|(^([2-9][0-9][0][48])([-\\/])(0?2)([-\\/])(29)$)|(^([1][89][2468][048])([-\\/])(0?2)([-\\/])(29)$)|(^([2-9][0-9][2468][048])([-\\/])(0?2)([-\\/])(29)$)|(^([1][89][13579][26])([-\\/])(0?2)([-\\/])(29)$)|(^([2-9][0-9][13579][26])([-\\/])(0?2)([-\\/])(29))|(((((0[13578])|([13578])|(1[02]))[\\-\\/\\s]?((0[1-9])|([1-9])|([1-2][0-9])|(3[01])))|((([469])|(11))[\\-\\/\\s]?((0[1-9])|([1-9])|([1-2][0-9])|(30)))|((02|2)[\\-\\/\\s]?((0[1-9])|([1-9])|([1-2][0-9]))))[\\-\\/\\s]?\\d{4})(\\s(((0[1-9])|([1-9])|(1[0-2]))\\:([0-5][0-9])((\\s)|(\\:([0-5][0-9])\\s))([AM|PM|am|pm]{2,2})))?$";
                        break;

                    case OptionItemType.Mobile:
                        itit.Pattern = @"^[0-9]{11}$";
                        break;

                    case OptionItemType.Telephone:
                        itit.Pattern = @"^(\\(\\d{3,4}\\)|\\d{3,4}-|\\s)?\\d{8}$";
                        break;

                    case OptionItemType.Fax:
                        itit.Pattern = @"^[+]{0,1}(\\d){1,3}[ ]?([-]?((\\d)|[ ]){1,12})+$";
                        break;

                    case OptionItemType.Func:
                        itit.Pattern = "myfun:" + itit.Func;
                        break;

                    case OptionItemType.Regex:
                        itit.Pattern = itit.Pattern.TrimStart('^').TrimEnd('$');
                        itit.Pattern = string.Format("^{0}$", itit.Pattern);
                        itit.Pattern = itit.Pattern.Replace(@"\", @"\\");
                        break;
                    }
                    itemsCode.AppendFormat("bindValidation{0}('{1}',{{   tip:'{2}',pattern:'{3}',placeholder:'{4}',isRequired:{5} }},{6},{7})", uk, item.FormFiledName, itit.Tip, itit.Pattern, item.Placeholder, item.IsRequired ? "true" : "false", index, item.TypeParams.Count);
                    itemsCode.AppendLine();
                }
            }
            option.Script = string.Format(script, itemsCode.ToString(), uk);
            script        = null;
            itemsCode.Clear();
            option.PageKey  = pageKey;
            option.ItemList = itemList.ToList();
            ValidationOptionList.Add(option);
        }
コード例 #13
0
        private ValidationErrorCollection ValidateDependencyProperty(DependencyObject dependencyObject, DependencyProperty dependencyProperty, ValidationManager manager)
        {
            ValidationErrorCollection errors = new ValidationErrorCollection();

            Attribute[]      attributes    = dependencyProperty.DefaultMetadata.GetAttributes(typeof(ValidationOptionAttribute));
            ValidationOption option        = (attributes.Length > 0) ? ((ValidationOptionAttribute)attributes[0]).ValidationOption : ValidationOption.Optional;
            Activity         propertyOwner = manager.Context[typeof(Activity)] as Activity;

            if (propertyOwner == null)
            {
                throw new InvalidOperationException(SR.GetString("Error_ContextStackItemMissing", new object[] { typeof(Activity).FullName }));
            }
            PropertyValidationContext context = new PropertyValidationContext(propertyOwner, dependencyProperty);

            manager.Context.Push(context);
            try
            {
                if (dependencyProperty.DefaultMetadata.DefaultValue != null)
                {
                    if (!dependencyProperty.PropertyType.IsValueType && (dependencyProperty.PropertyType != typeof(string)))
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_PropertyDefaultIsReference", new object[] { dependencyProperty.Name }), 0x1a8));
                    }
                    else if (!dependencyProperty.PropertyType.IsAssignableFrom(dependencyProperty.DefaultMetadata.DefaultValue.GetType()))
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_PropertyDefaultTypeMismatch", new object[] { dependencyProperty.Name, dependencyProperty.PropertyType.FullName, dependencyProperty.DefaultMetadata.DefaultValue.GetType().FullName }), 0x1a9));
                    }
                }
                object propValue = null;
                if (dependencyObject.IsBindingSet(dependencyProperty))
                {
                    propValue = dependencyObject.GetBinding(dependencyProperty);
                }
                else if (!dependencyProperty.IsEvent)
                {
                    propValue = dependencyObject.GetValue(dependencyProperty);
                }
                if ((propValue == null) || (propValue == dependencyProperty.DefaultMetadata.DefaultValue))
                {
                    if (dependencyProperty.IsEvent)
                    {
                        propValue = dependencyObject.GetHandler(dependencyProperty);
                        if (propValue == null)
                        {
                            propValue = WorkflowMarkupSerializationHelpers.GetEventHandlerName(dependencyObject, dependencyProperty.Name);
                        }
                        if ((propValue is string) && !string.IsNullOrEmpty((string)propValue))
                        {
                            errors.AddRange(this.ValidateEvent(propertyOwner, dependencyProperty, propValue, manager));
                        }
                    }
                    else
                    {
                        propValue = dependencyObject.GetValue(dependencyProperty);
                    }
                }
                bool flag = (propertyOwner.Parent != null) || ((propertyOwner is CompositeActivity) && (((CompositeActivity)propertyOwner).EnabledActivities.Count != 0));
                if (((option == ValidationOption.Required) && ((propValue == null) || ((propValue is string) && string.IsNullOrEmpty((string)propValue)))) && (dependencyProperty.DefaultMetadata.IsMetaProperty && flag))
                {
                    errors.Add(ValidationError.GetNotSetValidationError(base.GetFullPropertyName(manager)));
                    return(errors);
                }
                if (propValue == null)
                {
                    return(errors);
                }
                if (propValue is IList)
                {
                    PropertyValidationContext context2 = new PropertyValidationContext(propValue, null, string.Empty);
                    manager.Context.Push(context2);
                    try
                    {
                        foreach (object obj3 in (IList)propValue)
                        {
                            errors.AddRange(ValidationHelpers.ValidateObject(manager, obj3));
                        }
                        return(errors);
                    }
                    finally
                    {
                        manager.Context.Pop();
                    }
                }
                if (dependencyProperty.ValidatorType != null)
                {
                    Validator validator = null;
                    try
                    {
                        validator = Activator.CreateInstance(dependencyProperty.ValidatorType) as Validator;
                        if (validator == null)
                        {
                            errors.Add(new ValidationError(SR.GetString("Error_CreateValidator", new object[] { dependencyProperty.ValidatorType.FullName }), 0x106));
                            return(errors);
                        }
                        errors.AddRange(validator.Validate(manager, propValue));
                        return(errors);
                    }
                    catch
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_CreateValidator", new object[] { dependencyProperty.ValidatorType.FullName }), 0x106));
                        return(errors);
                    }
                }
                errors.AddRange(ValidationHelpers.ValidateObject(manager, propValue));
            }
            finally
            {
                manager.Context.Pop();
            }
            return(errors);
        }
コード例 #14
0
 public ValidationOptionAttribute(ValidationOption validationOption)
 {
     this.validationOption = validationOption;
 }
コード例 #15
0
        private ValidationErrorCollection ValidateDependencyProperty(DependencyObject dependencyObject, DependencyProperty dependencyProperty, ValidationManager manager)
        {
            ValidationErrorCollection errors = new ValidationErrorCollection();

            Attribute[]      validationVisibilityAtrributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(ValidationOptionAttribute));
            ValidationOption validationVisibility           = (validationVisibilityAtrributes.Length > 0) ? ((ValidationOptionAttribute)validationVisibilityAtrributes[0]).ValidationOption : ValidationOption.Optional;

            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).FullName));
            }

            PropertyValidationContext propertyValidationContext = new PropertyValidationContext(activity, dependencyProperty);

            manager.Context.Push(propertyValidationContext);

            try
            {
                if (dependencyProperty.DefaultMetadata.DefaultValue != null)
                {
                    if (!dependencyProperty.PropertyType.IsValueType &&
                        dependencyProperty.PropertyType != typeof(string))
                    {
                        errors.Add(new ValidationError(SR.GetString(SR.Error_PropertyDefaultIsReference, dependencyProperty.Name), ErrorNumbers.Error_PropertyDefaultIsReference));
                    }
                    else if (!dependencyProperty.PropertyType.IsAssignableFrom(dependencyProperty.DefaultMetadata.DefaultValue.GetType()))
                    {
                        errors.Add(new ValidationError(SR.GetString(SR.Error_PropertyDefaultTypeMismatch, dependencyProperty.Name, dependencyProperty.PropertyType.FullName, dependencyProperty.DefaultMetadata.DefaultValue.GetType().FullName), ErrorNumbers.Error_PropertyDefaultTypeMismatch));
                    }
                }

                // If an event is of type Bind, GetBinding will return the Bind object.
                object propValue = null;
                if (dependencyObject.IsBindingSet(dependencyProperty))
                {
                    propValue = dependencyObject.GetBinding(dependencyProperty);
                }
                else if (!dependencyProperty.IsEvent)
                {
                    propValue = dependencyObject.GetValue(dependencyProperty);
                }

                if (propValue == null || propValue == dependencyProperty.DefaultMetadata.DefaultValue)
                {
                    if (dependencyProperty.IsEvent)
                    {
                        // Is this added through "+=" in InitializeComponent?  If so, the value should be in the instance properties hashtable
                        // If none of these, its value is stored in UserData at design time.
                        propValue = dependencyObject.GetHandler(dependencyProperty);
                        if (propValue == null)
                        {
                            propValue = WorkflowMarkupSerializationHelpers.GetEventHandlerName(dependencyObject, dependencyProperty.Name);
                        }

                        if (propValue is string && !string.IsNullOrEmpty((string)propValue))
                        {
                            errors.AddRange(ValidateEvent(activity, dependencyProperty, propValue, manager));
                        }
                    }
                    else
                    {
                        // Maybe this is an instance property.
                        propValue = dependencyObject.GetValue(dependencyProperty);
                    }
                }

                // Be careful before changing this. This is the (P || C) validation validation
                // i.e. validate properties being set only if Parent is set or
                // a child exists.
                bool checkNotSet = (activity.Parent != null) || ((activity is CompositeActivity) && (((CompositeActivity)activity).EnabledActivities.Count != 0));

                if (validationVisibility == ValidationOption.Required &&
                    (propValue == null || (propValue is string && string.IsNullOrEmpty((string)propValue))) &&
                    (dependencyProperty.DefaultMetadata.IsMetaProperty) &&
                    checkNotSet)
                {
                    errors.Add(ValidationError.GetNotSetValidationError(GetFullPropertyName(manager)));
                }
                else if (propValue != null)
                {
                    if (propValue is IList)
                    {
                        PropertyValidationContext childContext = new PropertyValidationContext(propValue, null, String.Empty);
                        manager.Context.Push(childContext);

                        try
                        {
                            foreach (object child in (IList)propValue)
                            {
                                errors.AddRange(ValidationHelpers.ValidateObject(manager, child));
                            }
                        }
                        finally
                        {
                            System.Diagnostics.Debug.Assert(manager.Context.Current == childContext, "Unwinding contextStack: the item that is about to be popped is not the one we pushed.");
                            manager.Context.Pop();
                        }
                    }
                    else if (dependencyProperty.ValidatorType != null)
                    {
                        Validator validator = null;
                        try
                        {
                            validator = Activator.CreateInstance(dependencyProperty.ValidatorType) as Validator;
                            if (validator == null)
                            {
                                errors.Add(new ValidationError(SR.GetString(SR.Error_CreateValidator, dependencyProperty.ValidatorType.FullName), ErrorNumbers.Error_CreateValidator));
                            }
                            else
                            {
                                errors.AddRange(validator.Validate(manager, propValue));
                            }
                        }
                        catch
                        {
                            errors.Add(new ValidationError(SR.GetString(SR.Error_CreateValidator, dependencyProperty.ValidatorType.FullName), ErrorNumbers.Error_CreateValidator));
                        }
                    }
                    else
                    {
                        errors.AddRange(ValidationHelpers.ValidateObject(manager, propValue));
                    }
                }
            }
            finally
            {
                System.Diagnostics.Debug.Assert(manager.Context.Current == propertyValidationContext, "Unwinding contextStack: the item that is about to be popped is not the one we pushed.");
                manager.Context.Pop();
            }

            return(errors);
        }
コード例 #16
0
ファイル: ValidationLogic.cs プロジェクト: bbecker88/ePSE
        private bool Validate(object parameter, ValidationOption? Option)
        {
            if (!Option.HasValue)
                return true;

            if (parameter == null)
            {
                if ((Option.Value & ValidationOption.IsNull) != 0)
                    return true;
                return false;
            }

            var internParameter = parameter.ToString();

            if ((Option.Value & ValidationOption.IsNotNull) != 0)
            {
                if (parameter == null)
                    return false;
            }

            if ((Option.Value & ValidationOption.IsNull) != 0)
            {
                if (internParameter!= null)
                    return false;
            }

            if ((Option.Value & ValidationOption.IsNotEmpty) != 0)
            {
                if (internParameter.Trim().Length == 0)
                    return false;
            }

            if ((Option.Value & ValidationOption.IsEmpty) != 0)
            {
                if (internParameter.Trim().Length != 0)
                    return false;
            }

            if ((Option.Value & ValidationOption.IsNotNumber) != 0)
            {
                var number = 0;

                if (Int32.TryParse(internParameter, out number))
                    return false;
            }

            if ((Option.Value & ValidationOption.IsNumber) != 0)
            {
                var number = 0;

                if (!Int32.TryParse(internParameter, out number))
                    return false;
            }

            if ((Option.Value & ValidationOption.IsNotZero) != 0)
            {
                var number = -1;

                if (Int32.TryParse(internParameter, out number))
                {
                    if (number == 0)
                        return false;
                }
            }

            if ((Option.Value & ValidationOption.IsDate) != 0)
            {
                var date = DateTime.Today;

                if (!DateTime.TryParse(internParameter, out date))
                    return false;
            }

            if ((Option.Value & ValidationOption.IsBoolean) != 0)
            {
                var boolean = true;

                if (!Boolean.TryParse(internParameter, out boolean))
                    return false;
            }

            if ((Option.Value & ValidationOption.IsMail) != 0)
            {
                var regex = new Regex(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", RegexOptions.IgnoreCase);

                if (!regex.IsMatch(internParameter))
                    return false;
            }

            return true;
        }
コード例 #17
0
 public ValidationOptionAttribute(ValidationOption validationOption)
 {
     this.validationOption = validationOption;
 }