| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- using System;
- using System.Globalization;
- using System.Net;
- using System.Text.RegularExpressions;
- using System.Windows.Controls;
- namespace TeamAAS_VP.ValidationRules
- {
- public class SubnetMaskValidationRule : ValidationRule
- {
- public override ValidationResult Validate(object value, CultureInfo cultureInfo)
- {
- string input = value as string;
- // 检查输入是否为空
- if (string.IsNullOrWhiteSpace(input))
- return new ValidationResult(false, "Subnet mask cannot be empty.".Replace("\\n", Environment.NewLine).Replace("\\t", "\t"));
- // 检查是否包含全角字符
- if (ContainsFullWidthCharacters(input))
- return new ValidationResult(false, "Subnet mask contains full-width characters.".Replace("\\n", Environment.NewLine).Replace("\\t", "\t"));
- // 检查是否为有效的 IPv4 格式
- if (!IsValidIPv4Format(input))
- return new ValidationResult(false, "Invalid subnet mask format.".Replace("\\n", Environment.NewLine).Replace("\\t", "\t"));
- // 检查每个部分的数值是否在 0 到 255 之间
- if (!IsValidIPv4Range(input))
- return new ValidationResult(false, "Subnet mask out of range.".Replace("\\n", Environment.NewLine).Replace("\\t", "\t"));
- // 检查是否为有效的子网掩码
- if (!IsValidSubnetMask(input))
- return new ValidationResult(false, "Invalid subnet mask.".Replace("\\n", Environment.NewLine).Replace("\\t", "\t"));
- return ValidationResult.ValidResult;
- }
- // 检查是否包含全角字符
- private bool ContainsFullWidthCharacters(string input)
- {
- foreach (char c in input)
- {
- if (c >= 0xFF01 && c <= 0xFF5E) // 全角字符范围
- return true;
- }
- return false;
- }
- // 检查是否为有效的 IPv4 格式
- private bool IsValidIPv4Format(string input)
- {
- string pattern = @"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$";
- return Regex.IsMatch(input, pattern);
- }
- // 检查每个部分的数值是否在 0 到 255 之间
- private bool IsValidIPv4Range(string input)
- {
- string[] parts = input.Split('.');
- foreach (string part in parts)
- {
- if (!int.TryParse(part, out int number) || number < 0 || number > 255)
- return false;
- }
- return true;
- }
- // 检查是否为有效的子网掩码
- private bool IsValidSubnetMask(string input)
- {
- string[] parts = input.Split('.');
- int[] maskParts = new int[4];
- for (int i = 0; i < 4; i++)
- {
- maskParts[i] = int.Parse(parts[i]);
- }
- // 将子网掩码转换为二进制形式
- uint mask = (uint)(maskParts[0] << 24 | maskParts[1] << 16 | maskParts[2] << 8 | maskParts[3]);
- // 检查是否为连续的 1 和 0
- bool foundZero = false;
- for (int i = 31; i >= 0; i--)
- {
- uint bit = (mask >> i) & 1;
- if (bit == 0)
- {
- foundZero = true;
- }
- else if (foundZero)
- {
- // 如果发现 1 在 0 之后,说明不是有效的子网掩码
- return false;
- }
- }
- return true;
- }
- }
- }
|