using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Controls;
namespace CMWTAT_DIGITAL.Domain
{
class IsSN : ValidationRule
{
#region 匹配方法
///
/// 验证字符串是否匹配正则表达式描述的规则
///
/// 待验证的字符串
/// 正则表达式字符串
/// 是否匹配
public static bool IsMatch(string inputStr, string patternStr)
{
return IsMatch(inputStr, patternStr, false, false);
}
///
/// 验证字符串是否匹配正则表达式描述的规则
///
/// 待验证的字符串
/// 正则表达式字符串
/// 匹配时是否不区分大小写
/// 是否匹配
public static bool IsMatch(string inputStr, string patternStr, bool ifIgnoreCase)
{
return IsMatch(inputStr, patternStr, ifIgnoreCase, false);
}
///
/// 验证字符串是否匹配正则表达式描述的规则
///
/// 待验证的字符串
/// 正则表达式字符串
/// 匹配时是否不区分大小写
/// 是否验证空白字符串
/// 是否匹配
public static bool IsMatch(string inputStr, string patternStr, bool ifIgnoreCase, bool ifValidateWhiteSpace)
{
if (!ifValidateWhiteSpace && string.IsNullOrEmpty(inputStr))
return false;//如果不要求验证空白字符串而此时传入的待验证字符串为空白字符串,则不匹配
Regex regex = null;
if (ifIgnoreCase)
regex = new Regex(patternStr, RegexOptions.IgnoreCase);//指定不区分大小写的匹配
else
regex = new Regex(patternStr);
return regex.IsMatch(inputStr);
}
#endregion
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
//Console.WriteLine("\""+value+"\"");
//return string.IsNullOrWhiteSpace((value ?? "").ToString())
// ? new ValidationResult(false, "Key is required.")
// : ValidationResult.ValidResult;
string pattern = @"^[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}$";
if (IsMatch((value ?? "").ToString(), pattern))
{
return ValidationResult.ValidResult;
}
else if (string.IsNullOrWhiteSpace((value ?? "").ToString()))
{
return new ValidationResult(false, "Please enter the key for the current edition.");
}
else
{
return new ValidationResult(false, "Invalid format.");
}
}
}
}