如何验证Guid数据类型

本文关键字:Guid 数据类型 验证 何验证 | 更新日期: 2023-09-27 18:16:11

是否有验证GUID数据类型的方法?

我正在使用验证属性。http://msdn.microsoft.com/en-us/library/ee707335%28v=vs.91%29.aspx

如何验证Guid数据类型

您可以使用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}")]

您还可以创建自定义验证属性,这可能是一个更简洁的解决方案。

您可以编写您自己的CustomValidationAttribute子类,通过使用System的TryParse方法确保该值是一个向导。Guid(谢谢Jon!)。

我知道这个问题真的很老了,但我想我还是把我的答案加入进来,希望它能帮助其他人在未来寻找使用验证属性的最简单的解决方案。

我发现最好的解决方案是实现验证属性并使用微软的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; }

这样做的另一个好处是,如果应用程序正在验证API调用的请求体,而YourId不是一个有效的GUID,它将很好地返回一个400错误—并且响应体将具有您指定的错误消息(无效输入字符串。")。不需要编写自定义错误处理逻辑:)

此函数可能对您有所帮助....

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;
}

您可以删除静态或将函数放在某个实用程序类

这将使用。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; }

如果为该字段提供了以下任何一个,它将作为默认值(Guid)结束,并将被Validator捕获:

{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