Reputation: 97
Imagine that I have an endpoint that accepts optional MyParam
string array attribute.
How to check it if it's null or empty with most basic way - Data Annotations would be the best.
https://stackoverflow.com/questions/ask?MyParam=
[Required]
is not an option as parameter has to be optional[StringLength]
with MinimumLength doesn't work[MinLength]
doesn't work at all[RegularExpression(@"\S+")]
doesn't work at allUpdate: I want to do it on string array not just string, sorry about confusion. Hope this help to justify why above DataAnnotations don't work.
Upvotes: 2
Views: 1121
Reputation: 11340
I think what you're looking at here is a custom model validation attribute.
For example:
public class MyParamValidationAttribute : ValidationAttribute
{
public MyParamAttribute(string param)
{
Param = param;
}
public string Param { get; }
public string GetErrorMessage() =>
$"Invalid param value {param}.";
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var myParam = (string)value;
if (string.IsNullOrEmpty(myParam))
{
return new ValidationResult(GetErrorMessage());
}
return ValidationResult.Success;
}
}
Upvotes: 2