| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using System.Windows.Controls;
- namespace TeamAAS_VP.ValidationRules
- {
- public class CommentValidationRule : ValidationRule
- {
- // 最小长度和最大长度
- public int MinLength { get; set; } = 0;
- public int MaxLength { get; set; } = 256;
- // 验证方法
- public override ValidationResult Validate(object value, CultureInfo cultureInfo)
- {
- string input = value as string;
- if (!string.IsNullOrWhiteSpace(input))
- {
- string msg = "Content must be between {MinLength} and {MaxLength} characters.".Replace("\\n", Environment.NewLine).Replace("\\t", "\t");
- // 修复:计算字符串的实际长度,将汉字视为两个字符
- int actualLength = input.Length;// input.Sum(c => c > 127 ? 2 : 1);
- int count = input.Split(new string[] { "\r\n" }, StringSplitOptions.None).Length - 1;
- int charactersCount = actualLength - count;
- if (charactersCount < MinLength || charactersCount > MaxLength)
- {
- if (msg==null)
- {
- msg = "Content must be between {MinLength} and {MaxLength} characters.";
- }
- return new ValidationResult(false, msg.Replace("{MinLength}", MinLength.ToString()).Replace("{MaxLength}", MaxLength.ToString()));
- }
- }
- // 如果所有检查通过,返回验证成功
- return ValidationResult.ValidResult;
- }
- }
- }
|