[英]How can I validate Guid datatype?
有沒有辦法驗證 GUID 數據類型?
我正在使用驗證屬性。 http://msdn.microsoft.com/en-us/library/ee707335%28v=vs.91%29.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}")]
您還可以創建自定義驗證屬性,這可能是一種更簡潔的解決方案。
您可以使用 System.Guid 的TryParse 方法編寫自己的CustomValidationAttribute子類,以確保該值是一個 guid(感謝 Jon!)。
我知道這個問題真的很老,但我想我會補充我的答案,希望它可以幫助其他人在未來使用驗證屬性尋找最簡單的解決方案。
我發現最好的解決方案是實現驗證屬性並使用 Microsoft 的 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 錯誤 - 響應正文將包含您指定的錯誤消息(“無效的輸入字符串。”)。 無需編寫自定義錯誤處理邏輯:)
這將使用 .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),並會被驗證器捕獲:
{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;
}
您可以刪除靜態或將該功能放在某個實用程序類中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.