CommentValidationRule.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Threading.Tasks;
  8. using System.Windows.Controls;
  9. namespace TeamAAS_VP.ValidationRules
  10. {
  11. public class CommentValidationRule : ValidationRule
  12. {
  13. // 最小长度和最大长度
  14. public int MinLength { get; set; } = 0;
  15. public int MaxLength { get; set; } = 256;
  16. // 验证方法
  17. public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  18. {
  19. string input = value as string;
  20. if (!string.IsNullOrWhiteSpace(input))
  21. {
  22. string msg = "Content must be between {MinLength} and {MaxLength} characters.".Replace("\\n", Environment.NewLine).Replace("\\t", "\t");
  23. // 修复:计算字符串的实际长度,将汉字视为两个字符
  24. int actualLength = input.Length;// input.Sum(c => c > 127 ? 2 : 1);
  25. int count = input.Split(new string[] { "\r\n" }, StringSplitOptions.None).Length - 1;
  26. int charactersCount = actualLength - count;
  27. if (charactersCount < MinLength || charactersCount > MaxLength)
  28. {
  29. if (msg==null)
  30. {
  31. msg = "Content must be between {MinLength} and {MaxLength} characters.";
  32. }
  33. return new ValidationResult(false, msg.Replace("{MinLength}", MinLength.ToString()).Replace("{MaxLength}", MaxLength.ToString()));
  34. }
  35. }
  36. // 如果所有检查通过,返回验证成功
  37. return ValidationResult.ValidResult;
  38. }
  39. }
  40. }