有没有一种验证GUID数据类型的方法?
我正在使用验证属性。 http://msdn.microsoft.com/zh-cn/library/ee707335(v=vs.91).aspx
我正在使用验证属性。 http://msdn.microsoft.com/zh-cn/library/ee707335(v=vs.91).aspx
RegularExpressionAttribute
。以下是一个使用格式 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
的示例:[RegularExpression(Pattern = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")]
我知道这个问题很旧了,但是我想在这里提供我的答案,希望它能帮助未来寻找使用验证属性的最简单解决方案的人。
我发现最好的解决方案是实现验证属性并使用微软的TryParse方法(而不是编写自己的正则表达式):
public class ValidateGuid : System.ComponentModel.DataAnnotations.ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return System.Guid.TryParse(value.ToString(), out var guid) ? ValidationResult.Success : new ValidationResult("Invalid input string.");
}
}
[ValidateGuid]
public string YourId { get; set; }
这将使用 .Net 内置的 Guid 类型进行验证,因此您不必使用自定义正则表达式(这些正则表达式尚未经过 Microsoft 的严格测试):
public class RequiredGuidAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
var guid = CastToGuidOrDefault(value);
return !Equals(guid, default(Guid));
}
private static Guid CastToGuidOrDefault(object value)
{
try
{
return (Guid) value;
}
catch (Exception e)
{
if (e is InvalidCastException || e is NullReferenceException) return default(Guid);
throw;
}
}
}
然后,您只需像这样使用它:
[RequiredGuid]
public Guid SomeId { get; set; }
{someId:''}
{someId:'00000000-0000-0000-0000-000000000000'}
{someId:'XXX5B4C1-17DF-E511-9844-DC4A3E5F7697'}
{someMispelledId:'E735B4C1-17DF-E511-9844-DC4A3E5F7697'}
new Guid()
null //Possible when the Attribute is used on another type
SomeOtherType //Possible when the Attribute is used on another type
这个函数可能会对你有所帮助...
public static bool IsGUID(string expression)
{
if (expression != null)
{
Regex guidRegEx = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");
return guidRegEx.IsMatch(expression);
}
return false;
}
您可以移除静态关键字,或将该函数放入某个实用类中。