Ejemplo n.º 1
0
        /// <summary>
        /// Validates <paramref name="value"/> using the validators associated with the source property.
        /// </summary>
        /// <param name="value">The value from the binding target to check.</param>
        /// <param name="cultureInfo">The culture to use in this rule.</param>
        /// <returns>A <see cref="ValidationResult"/> object.</returns>
        public override SWC.ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            SWC.ValidationResult validationResult = SWC.ValidationResult.ValidResult;

            var validator = GetValidator();

            if (validator == null)
            {
                return(SWC.ValidationResult.ValidResult);
            }

            var results = validator.Validate(new ExternalValue {
                PropertyValue = value
            });

            if (!results.IsValid)
            {
                var errorContent =
                    results.Select(vr => vr.Message).Aggregate((acc, message) => acc + Environment.NewLine + message);

                validationResult = new SWC.ValidationResult(false, errorContent);
            }

            return(validationResult);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// This method is called to Validate the value.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="cultureInfo"></param>
        /// <returns></returns>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);
            decimal dValue = decimal.MinValue;
            bool isDecimal = false;

            if (value is decimal)
            {
                dValue = (decimal)value;
                isDecimal = true;
            }
            else
            {
                //Try to strip off any extra notation
                string val = value.ToString().Replace("$", "");
                isDecimal = decimal.TryParse(val, out dValue);
            }

            if (!isDecimal || dValue < MinValue || dValue > MaxValue)
            {
                if (ErrorMessage == null)
                    ErrorMessage = string.Format(_errorMessage, MinValue.ToString("N"), MaxValue.ToString("N"));

                result = new ValidationResult(false, this.ErrorMessage);
            }

            return result;
        }
        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);

            try
            {
                string inputString = (value ?? string.Empty).ToString().Trim();
                
                int x;
                bool converted = int.TryParse(inputString, out x);
                if (_empty && inputString.Length == 0) return result = new ValidationResult(true, null);
                if (!converted)
                {
                    return result = new ValidationResult(false, ErrorMessage);
                }
                
                if ((inputString.Length > _maximum) || (inputString.Length < _minimum)) result = new ValidationResult(false, ErrorMessage);
                return result;   
                
            }
            catch (Exception ex)
            {
                return new ValidationResult(false, ex.Message);
            }
            
           
        }
        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);


            switch (TypeRegax)
            {
                case "email":
                    patternStrict = email;
                    break;
                case "ipaddress":
                    patternStrict = ip;
                    break;
            }

                string inputString = (value ?? string.Empty).ToString().Trim();

                if (_empty && inputString.Length == 0) return result = new ValidationResult(true, null);

                Regex reStrict = new Regex(patternStrict);
                bool isStrictMatch = reStrict.IsMatch(inputString);
                if (!isStrictMatch)
                {
                    result = new ValidationResult(false, this.ErrorMessage);
                }

                return result;
        }
Ejemplo n.º 5
0
        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);

            const string errorMsg = "Expected a hex string that represents a byte array. Example: 45 F3 C5 1A... (spaces between bytes not required)\nNote: An even number of characters is required as 2 hex characters represent one byte";
            try
            {
                if (value == null)
                {
                    result = new ValidationResult(false, errorMsg);
                }

                string str = value as string;
                str = Regex.Replace(str, @"\s+", ""); // remove all whitespace
                if (str.Length > 0)
                {
                    for (int i = 0; i < str.Length; i += 2)
                    {
                        byte b = Convert.ToByte(str.Substring(i, 2), 16);
                    }
                }
            }
            catch (FormatException ex)
            {
                result = new ValidationResult(false, errorMsg + "\n\n" + ex.Message);
            }
            catch (Exception ex)
            {
                result = new ValidationResult(false, errorMsg + "\n\n" + ex.Message);
            }

            return result;
        }
Ejemplo n.º 6
0
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            ValidationResult result;
            string val = (string) value;

            #region check whether empty or non-numeric
            if (string.IsNullOrEmpty(val))
            {
                return new ValidationResult(true, "");
            }

            if (Nonnumeric.IsMatch(val))
            {
                return  new ValidationResult(true, "");
            }
            #endregion

            Boolean thousandsValid = false;
            try
            {
                Double.Parse(val, ThousandStyles);
                if (!(Settings.Default.SifUseThousandsSeparator || ignoreLocal))
                {
                    thousandsValid = true;
                    Double.Parse(val, NormalStyles);
                }
                result = new ValidationResult(true, "");
            }
            catch (FormatException e)
            {
                if (thousandsValid && !ignoreLocal)
                {
                    var messageBox = new NumberValidationMessageBox();
                    DialogResult userChoice = messageBox.ShowDialog();
                    switch (userChoice)
                    {
                        case (DialogResult.Yes) :
                            ignoreLocal = true;
                            break;
                        case (DialogResult.Ignore) :
                            Settings.Default.SifUseThousandsSeparator = true;
                            break;
                    }

                    // get the validation result without asking infinite times
                    bool old = ignoreLocal;
                    ignoreLocal = true;
                    result = Validate(value, cultureInfo);
                    ignoreLocal = old;
                } 
                else 
                {
                    result = new ValidationResult(false, e.Message);
                }
            }

            return result;
        }
Ejemplo n.º 7
0
 public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
 {
     ValidationResult result = new ValidationResult(true, null);
     if (String.IsNullOrWhiteSpace(value as string))
     {
         result = new ValidationResult(false, errorMessage ?? "emptyString!!");
     }
     return result;
 }
 public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
 {
     ValidationResult result = new ValidationResult(true, null);
     if (value == null || object.ReferenceEquals(value, DBNull.Value))
     {
         result = new ValidationResult(false, "Required!");
     }
     return result;
 }
 public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
 {
     ValidationResult result = new ValidationResult(true, null);
     if (value == null || (value is string && string.IsNullOrWhiteSpace(value.ToString())))
     {
         result = new ValidationResult(false, "真实姓名不能为空!");
     }
     return result;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// When overridden in a derived class, performs validation checks on a value.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Windows.Controls.ValidationResult"/> object.
        /// </returns>
        /// <param name="value">The value from the binding target to check.</param>
        /// <param name="cultureInfo">The culture to use in this rule.</param>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var fail = new ValidationResult(false, Constants.Validation.NotEmptyInputRuleMessage);

            if (value == null) return fail;

            return string.IsNullOrWhiteSpace(value.ToString())
                ? fail
                : new ValidationResult(true, null);
        }
Ejemplo n.º 11
0
        public override System.Windows.Controls.ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var result = new System.Windows.Controls.ValidationResult(true, null);

            if (!value.ToString().ToLower().Equals("male") && !value.ToString().ToLower().Equals("female"))
            {
                result = new System.Windows.Controls.ValidationResult(false, "Gender should be Male of Female");
            }
            return(result);
        }
 public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
 {
     ValidationResult result = new ValidationResult(true, null);
     this.birthday = (value ?? string.Empty).ToString();
     if (this.birthday == null || string.IsNullOrWhiteSpace(this.birthday))
     {
         result = new ValidationResult(false, "生日不能为空!");
     }
     return result;
 }
Ejemplo n.º 13
0
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            ValidationResult result = ValidationResult.ValidResult;
            if (string.IsNullOrEmpty(value as string))
            {
                result = new ValidationResult(false, ValidationResources.NoClassName);
            }

            return result;
        }
Ejemplo n.º 14
0
        public void Test_Illegal_Characters()
        {
            RangeRule val = new RangeRule();

            val.Min = 1;
            val.Max = 20;

            ValidationResult vr = new ValidationResult(false, "Illegal characters");

            Assert.AreEqual(val.Validate("ugh", new System.Globalization.CultureInfo("en-us")), vr);
        }
Ejemplo n.º 15
0
//		http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation
		public override ValidationResult Validate(object value, CultureInfo cultureInfo)
		{
			ValidationResult result = new ValidationResult(true, null);
			var str = value.ToString();
			var y = 0;
			var res = Int32.TryParse(str,NumberStyles.HexNumber,CultureInfo.InvariantCulture,out y);
			if (!res) {
				 result = new ValidationResult(false, "No valid Hex Digit");
			}
			return result;
		}
Ejemplo n.º 16
0
        public void Test_Validated()
        {
            RangeRule val = new RangeRule();

            val.Min = 1;
            val.Max = 20;

            ValidationResult vr = new ValidationResult(true, null);

            Assert.AreEqual(val.Validate("5", new System.Globalization.CultureInfo("en-us")), vr);
        }
        public override ValidationResult Validate(object value, CultureInfo culture, CellValidationContext context)
        {
            ValidationResult result = null;

            // not empty check
            bool isObjectEmpty = true;
            if (null != value)
                isObjectEmpty = string.IsNullOrEmpty(value.ToString().Trim()); // project name cannot consist only in blanks
            if (isObjectEmpty)
                result = new ValidationResult(false, (string)Application.Current.FindResource("ProjectNameValidationRuleIncorrectNameError"));

            if (null == result)
            {
                string name = value.ToString().Trim();
                if (-1 != name.IndexOfAny(new char[] {'\\', '/', '*', ';', ',', ':', '|', '"'}))
                    result = new ValidationResult(false, (string)Application.Current.FindResource("ProjectNameValidationRuleIncorrectNameError"));
                else
                {
                    ProjectsPage projectsPage = (ProjectsPage)App.Current.MainWindow.GetPage(PagePaths.ProjectsPagePath);
                    ProjectDataWrapper currentItem = (ProjectDataWrapper)projectsPage.XceedGrid.CurrentItem;

                    // check duplicate
                    ItemCollection wrappedCollection = projectsPage.XceedGrid.Items;
                    foreach (ProjectDataWrapper wrapper in wrappedCollection)
                    {
                        if (name.Equals(wrapper.Name, StringComparison.InvariantCultureIgnoreCase) && (wrapper != currentItem))
                        {
                            result = new ValidationResult(false, (string)App.Current.FindResource("ProjectNameValidationRuleDuplicateNameError"));
                            break; // NOTE: exit - error founded
                        }
                    }

                    if (null == result)
                    {   // normal length check
                        string fileName = name + ProjectConfiguration.FILE_EXTENSION; // NOTE: check only one file name,
                            // but real created two files: ProjectConfiguration.FILE_EXTENSION and DatabaseEngine.DATABASE_EXTENSION
                        string filePath = null;
                        try
                        {
                            filePath = _GetDatabaseAbsolutPath(App.Current.ProjectCatalog.FolderPath, fileName);
                        }
                        catch
                        {
                        }

                        // valid name check
                        if (!FileHelpers.IsFileNameCorrect(filePath) || !FileHelpers.ValidateFilepath(filePath))
                            result = new ValidationResult(false, (string)Application.Current.FindResource("ProjectNameValidationRuleIncorrectNameError"));
                    }
                }
            }

            return (null == result)? ValidationResult.ValidResult : result;
        }
Ejemplo n.º 18
0
        public void Test_Out_Of_Range()
        {
            RangeRule val = new RangeRule();

            val.Min = 1;
            val.Max = 20;

            ValidationResult vr = new ValidationResult(false, "Please enter a number in the given range.");

            Assert.AreEqual(val.Validate("50", new System.Globalization.CultureInfo("en-us")), vr);
        }
 public override ValidationResult Validate(object value, CultureInfo cultureInfo)
 {
     var result = new ValidationResult(true, null);
     int inputString = int.Parse(value.ToString());
     if (inputString < this.MinimumLength ||
            (this.MaximumLength > 0 &&
             inputString > this.MaximumLength))
     {
         result = new ValidationResult(false, this.ErrorMessage);
     }
     return result;
 }
 public override ValidationResult Validate(object value, CultureInfo cultureInfo)
 {
     var result = new ValidationResult(true, null);
     int ageValue = (int)float.Parse(value.ToString());
     if (ageValue < this.MinimumAge ||
            (this.MaximumAge > 0 &&
             ageValue > this.MaximumAge))
     {
         result = new ValidationResult(false, this.ErrorMessage);
     }
     return result;
 }
 public override ValidationResult Validate(object value,
     CultureInfo cultureInfo)
 {
     ValidationResult result = new ValidationResult(true, null);
     string inputString = (value ?? string.Empty).ToString();
     if (inputString.Length < this.MinimumLength ||
            (this.MaximumLength > 0 &&
             inputString.Length > this.MaximumLength))
     {
         result = new ValidationResult(false, this.ErrorMessage);
     }
     return result;
 }
Ejemplo n.º 22
0
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);

            if (!string.IsNullOrEmpty(_pattern))
            {
                if (!Regex.IsMatch((value ?? String.Empty).ToString(), _pattern))
                {
                    result = new ValidationResult(false, ErrorMessage);
                }
            }

            return result;
        }
Ejemplo n.º 23
0
 public override ValidationResult Validate(object value, CultureInfo cultureInfo)
 {
     ValidationResult result;
     try
     {
     }
     catch (Exception ex)
     {
         result = new ValidationResult(false, "Illegal characters or " + ex.Message);
         return result;
     }
     result = new ValidationResult(true, null);
     return result;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <param name="cultureInfo"></param>
        /// <returns></returns>
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            var result = ValidationResult.ValidResult;
            var enteredvalue = string.Format("{0}", value);

            var patternbuilder = new StringBuilder("[a-zA-Z]");
            if(!Regex.IsMatch(enteredvalue,patternbuilder.ToString()) )
            {
                result = new ValidationResult(false,
                                string.Format("Invalid entry:{0} :only alpha characters are permitted",enteredvalue));

            }
            return result;
        }
Ejemplo n.º 25
0
        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);

            UInt64 num = 0;

            try
            {
                if (value == null)
                {
                    result = new ValidationResult(false, "Expected a number");
                }

                string str = value as string;
                if (str == "")
                {
                }
                else if (str.ToLower().StartsWith("0x") == true)
                {
                    num = System.Convert.ToUInt64(str.Substring(2), 16);
                }
                else if (str.ToLower().EndsWith("h") == true)
                {
                    num = System.Convert.ToUInt64(str.Substring(0, str.Length-1), 16);
                }
                else
                {
                    num = System.Convert.ToUInt64(str);
                }

                if (num < MinimumValue || num > MaximumValue)
                {
                    if (Hex == true)
                        result = new ValidationResult(false, "The value must be in the following range: " + MinimumValue.ToString("X2") + "-" + MaximumValue.ToString("X2"));
                    else
                        result = new ValidationResult(false, "The value must be in the following range: " + MinimumValue + "-" + MaximumValue);
                }
            }
            catch (FormatException ex)
            {
                result = new ValidationResult(false, ex.Message);
            }
            catch (Exception ex)
            {
                result = new ValidationResult(false, ex.Message);
            }

            return result;
        }
Ejemplo n.º 26
0
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);
            int temp = 0;
            bool res = int.TryParse((string)value, out temp);
            if (!res || temp > 100)
            {
                string msg = "";
                CommonStaticMethod.GetLanguageString("显示屏的亮度范围是:(0%~100%)", "Lang_Bright_ScreenBrightRange", out msg);
                result = new ValidationResult(false, msg);
            }

            return result;

        }
 public LoginDialogWindow()
 {
     InitializeComponent();
     DataContext = new LoginPresenter(this);
     _indeterminateLoading = new LoadingControl();
     _indeterminateLoading.Margin = new Thickness(0, 20, 0, 0);
     _errorMessage = new ErrorControl();
     var varRes = new ValidationResult(true, null);
     _errorMessage.BtnOk.Click += BtnOk_Click;
     Loaded += (s, e) => { ClearErrors(); };
     Closed += (s, e) =>
     {
         if (!_manualClosing && LoginCanceled != null)
             LoginCanceled(s, e);
     };
 }
Ejemplo n.º 28
0
 public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
 {
     ValidationResult result = new ValidationResult(true, null);
     this.email = (value ?? string.Empty).ToString();
     if (this.email == null || string.IsNullOrWhiteSpace(this.email))
     {
         result = new ValidationResult(false, "Email不能为空!");
     }
     else
     {
         if (!ValidationUtil.IsValidEmail(this.email))
         {
             result = new ValidationResult(false, "Email格式不正确,请重新输入!");
         }
     }
     return result;
 }
 public override ValidationResult Validate(
     object value,
     System.Globalization.CultureInfo cultureInfo)
 {
     string valueAsString = value as string;
     ValidationResult result = ValidationResult.ValidResult;
     ushort level;
     if (string.IsNullOrEmpty(valueAsString))
     {
         result = new ValidationResult(false, ValidationResources.NoLevel);
     }
     else if (!ushort.TryParse(valueAsString, out level) || level > 5)
     {
         result = new ValidationResult(false, ValidationResources.InvalidLevel);
     }
     return result;
 }
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var numberInputVal = new NumberInputValidationRule();
            var result = numberInputVal.Validate(value, cultureInfo);
            if (!result.IsValid)
                return result;

            double v = Convert.ToDouble(value);

            if (v < Min || v > Max)
            {
                result = new ValidationResult(false, string.Format("Value should be in the range of [{0},{1}]", Min, Max));
                return result;
            }

            return new ValidationResult(true, string.Empty);
        }
    public override ValidationResult Validate( object value, CultureInfo cultureInfo )
    {
      ValidationResult result = new ValidationResult( true, null );

      if( GeneralUtilities.CanConvertValue( value, _type ) )
      {
        try
        {
          _propertyTypeConverter.ConvertFrom( value );
        }
        catch( Exception e )
        {
          // Will display a red border in propertyGrid
          result = new ValidationResult( false, e.Message );
        }
      }
      return result;
    }
        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);

            try
            {
                string inputString = (value ?? string.Empty).ToString().Trim();
                
                int x;
                bool converted = int.TryParse(inputString, out x);
                if (_empty && inputString.Length == 0) return result = new ValidationResult(true, null);
                if (!converted)
                {
                    return result = new ValidationResult(false, ErrorMessage);
                }
                
                if ((inputString.Length > _maximum) || (inputString.Length < _minimum)) result = new ValidationResult(false, ErrorMessage);

                if (inputString.Length == Maximum)
                {
                        using (FixedAssetServiceClient client = new FixedAssetServiceClient())
                        {
                            client.Open();
                            FixedAsset dev = client.GetFixedAssetById(x);
                            client.Close();
                            if (dev == null)
                            {
                                result = new ValidationResult(false, "Podany środek trwały nie istnieje");
                            }
                        }
                }
                
                return result;   
                
            }
            catch (Exception ex)
            {
                return new ValidationResult(false, ex.Message);
            }
            
           
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Validates all properties on the current data source.
        /// </summary>
        /// <returns>True if there are no errors displayed, otherwise false.</returns>
        /// <remarks>
        /// Note that only errors on properties that are displayed are included. Other errors, such as errors for properties that are not displayed,
        /// will not be validated by this method.
        /// </remarks>
        public bool Validate()
        {
            bool isValid = true;

            _firstInvalidElement = null;
            errorMessages        = new List <string>();

            FindBindingsRecursively(Parent,
                                    delegate(FrameworkElement element, Binding binding, DependencyProperty dp)
            {
                foreach (ValidationRule rule in binding.ValidationRules)
                {
                    System.Windows.Controls.ValidationResult valid = rule.Validate(element.GetValue(dp), CultureInfo.CurrentUICulture);
                    if (!valid.IsValid)
                    {
                        if (isValid)
                        {
                            isValid = false;
                            _firstInvalidElement = element;
                        }

                        BindingExpression expression = element.GetBindingExpression(dp);
                        ValidationError error        = new ValidationError(rule, expression, valid.ErrorContent, null);
                        System.Windows.Controls.Validation.MarkInvalid(expression, error);

                        string errorMessage = valid.ErrorContent.ToString();
                        if (!errorMessages.Contains(errorMessage))
                        {
                            errorMessages.Add(errorMessage);
                        }
                    }
                }
            });

            return(isValid);
        }
 /// <summary>
 /// Determines whether the collection contains an equivalent ValidationResult
 /// </summary>
 /// <param name="collection">ValidationResults to search through</param>
 /// <param name="target">ValidationResult to search for</param>
 /// <returns></returns>
 public static bool ContainsEqualValidationResult(this ICollection <ValidationResult> collection, ValidationResult target)
 {
     return(collection.FindEqualValidationResult(target) != null);
 }
        /// <summary>
        /// Finds an equivalent ValidationResult if one exists.
        /// </summary>
        /// <param name="collection">ValidationResults to search through.</param>
        /// <param name="target">ValidationResult to find.</param>
        /// <returns>Equal ValidationResult if found, null otherwise.</returns>
        public static ValidationResult FindEqualValidationResult(this ICollection <ValidationResult> collection, ValidationResult target)
        {
            foreach (ValidationResult oldValidationResult in collection)
            {
                if (oldValidationResult.ErrorMessage == target.ErrorMessage)
                {
                    bool movedOld    = true;
                    bool movedTarget = true;
                    IEnumerator <string> oldEnumerator    = oldValidationResult.MemberNames.GetEnumerator();
                    IEnumerator <string> targetEnumerator = target.MemberNames.GetEnumerator();
                    while (movedOld && movedTarget)
                    {
                        movedOld    = oldEnumerator.MoveNext();
                        movedTarget = targetEnumerator.MoveNext();

                        if (!movedOld && !movedTarget)
                        {
                            return(oldValidationResult);
                        }
                        if (movedOld != movedTarget || oldEnumerator.Current != targetEnumerator.Current)
                        {
                            break;
                        }
                    }
                }
            }
            return(null);
        }