Is there a way to validate GUID datatype?
I'm using validation attributes. http://msdn.microsoft.com/en-us/library/ee707335%28v=vs.91%29.aspx
Is there a way to validate GUID datatype?
I'm using validation attributes. http://msdn.microsoft.com/en-us/library/ee707335%28v=vs.91%29.aspx
You can use a RegularExpressionAttribute
. Here's a sample using the format 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}")]
You can also create a custom validation attribute, which is probably a cleaner solution.
You could write your own subclass of CustomValidationAttribute that ensures the value is a guid by using the TryParse method of System.Guid (thanks Jon!).
I know this question is really old, but thought I'll chip in my answer in hope that it can help others in the future looking for the simplest solution using Validation Attribute.
I've found that the best solution is to implement the Validation Attribute and use Microsoft's TryParse method (instead of writing our own regex):
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.");
}
}
And then use it like this:
[ValidateGuid]
public string YourId { get; set; }
The additional good thing about this is that if the application is validating the request body of an API call and YourId is not a valid GUID, it will nicely response back with a 400 error - and the response body will have the error message that you specified ("Invalid input string."). No need to write custom error-handling logic :)
This function might help you....
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;
}
You may remove the static or put the function in some Utility Class
This will use .Net's built-in Guid type for the validation, so you don't have to use a custom regular expression (which hasn't undergone Microsoft's rigorous testing):
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;
}
}
}
You then just use it like this:
[RequiredGuid]
public Guid SomeId { get; set; }
If any of the following are provided to this field, it will end up as a default(Guid), and will be caught by the 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
Based on @ABVincita's answer I'm using this one:
using System.ComponentModel.DataAnnotations;
namespace MyProject.Common.Attributes
{
public class ValidGuidAttribute : ValidationAttribute
{
public ValidGuidAttribute() : base("The field {0} must be a valid GUID.")
{
}
public override bool IsValid(object value)
{
return System.Guid.TryParse(value.ToString(), out var guid);
}
}
}
To use it on a property:
[ValidGuid]
public string ApiId { get; set; }
The error message will also show the name of the field not having a valid GUID.
© 2022 - 2024 — McMap. All rights reserved.