Demis, would you consider modifying the Required attribute and StringLength attributes to have a CONDITIONAL MinimumLength parameter. By allowing the RequiredAttribute to accept an optional boolean of false, the property can become optional. In turn, the MinimumLength parameter would only be evaluated when a value is actually supplied.
For example, our sample DTO contains a string parameter “UpdatedByMemberId” which must either be null or contain a valid UID of 32 characters. By setting these two values as described above we are able to truly validate this condition when a value is actually set…
[Required(false)]
[StringLength(32, MinimumLength = 32)]
public string AuditUpdatedByMemberId { get; set; }
The attributes’ current functionality force validation of this nature to be handled by the application (and for bad data to be supplied). Since the only way to have an optional UID would be to NOT use the RequiredAttribute and to NOT set the MinimumLength parameter. In this scenario, any value of 32 characters or less could be supplied.
Can’t you just use a Guid? datatype?
Fredrick Lackey:
In this scenario, unfortunately, no. The app needs to be compatible with both Oracle and SQL Server, which means the braces and dashes must not exist (ie RAW(32), char(32), etc.). But the theory is more about being able to check the MinimumLength only when a value is supplied… not just for a Guid. For example, we might have a SecretAnswer field that may be null OR a minimum of 3 characters.
A Guid can coerce a UUID in a string in multiple formats.
Honestly it’s better to use C# validation when you need it, that combination of attrs is less flexible and doesn’t appear to be any more readable. It would also only be validated in OrmLite and not at the Request DTO.