GUID データ型を検証する方法はありますか?
検証属性を使用しています。 http://msdn.microsoft.com/en-us/library/ee707335%28v=vs.91%29.aspx
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 メソッドを使用して、値が GUID であることを保証するCustomValidationAttributeの独自のサブクラスを作成できます(Jon に感謝します)。
この関数はあなたを助けるかもしれません...
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) になり、バリデータによってキャッチされます。
{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