RegexRule.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System.Globalization;
  2. using System.Windows.Controls;
  3. using HandyControl.Data;
  4. namespace HandyControl.Tools;
  5. public class RegexRule : ValidationRule
  6. {
  7. public TextType Type { get; set; }
  8. public string Pattern { get; set; }
  9. public string ErrorContent { get; set; } = Properties.Langs.Lang.FormatError;
  10. public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  11. {
  12. if (value is not string text)
  13. {
  14. return CreateErrorValidationResult();
  15. }
  16. if (!string.IsNullOrEmpty(Pattern))
  17. {
  18. if (!text.IsKindOf(Pattern))
  19. {
  20. return CreateErrorValidationResult();
  21. }
  22. }
  23. else if (Type != TextType.Common)
  24. {
  25. if (!text.IsKindOf(Type))
  26. {
  27. return CreateErrorValidationResult();
  28. }
  29. }
  30. return ValidationResult.ValidResult;
  31. }
  32. private ValidationResult CreateErrorValidationResult()
  33. {
  34. return new ValidationResult(false, ErrorContent);
  35. }
  36. }