I Have a Problem with Empty GUIDs!

Hasangi Kahaduwa
2 min readMay 6, 2019

Whenever you are working on a REST API development, no matter what the technology you use, model validation is considered as a ground rule to adhere. From this story I am going to talk about a specific incident of Model Validation when using .Net Framework.

Data Annotation in .NET Framework

.NET Framework has already provided Data Annotation feature which could be used in Model Validation just by adding attribute tags as shown in the example below.

 public class Command : IRequest<BaseResponse>{[Required]public string Name { get; set; }[Required]public string DisplayName { get; set; }}

In the above example it is shown that, Name and DisplayName attributes are essential in the request body. The Required attribute tag which comes along with the Data Annotation feature of the .NET Framework, specifies that when a field on a form is validated, the field must contain a value. A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.

However, when it comes to the RequiredAttribute tag, this above validation rule is not valid for GUIDs.

What are GUIDs?

GUID stands for Global Unique Identifier. Whenever an unique identifier is required this, 128-bit integer (16 bytes) could be used.

GUID inherits from struct class. Therefore, the default value of GUID is an instance of Guid.Empty.

Guid.Empty however satisfies the conditions of RequiredAttribute.

How to Validate Empty GUIDs?

Actually, this is what I wanted to talk about.

Since RequiredAttribute will not be enough to check the emptiness of a GUID, we will have to create a custom attribute which is capable of validating the emptiness of the GUID.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,AllowMultiple = false)]public class NotEmptyGuidAttribute : ValidationAttribute{public const string ErrorMessage = “The {0} field must not be empty”;public NotEmptyGuidAttribute() : base(ErrorMessage) { }public override bool IsValid(object value){if (value is null)return true; // Allows to return a null valueswitch (value){case Guid guid:return guid != Guid.Empty; //Checks whether the GUID is empty or not and returns false if GUID is emptydefault:return true;}}}

Then you can use this NotEmptyGuidAttribute as an attribute tag for GUIDs and validate the model for non-empty GUIDs as follows,

public class Command : IRequest<BaseResponse>{[Required]public string Name { get; set; }[Required][NotEmptyGuid]public Guid DepartmentId { get; set; }}

Though there are several other hacks available, this is the best practice.

Hope this would be useful at some point to you..

Kudos!!

--

--