ASP.NET Core provides a way for us to create custom validations for our requests by extending ValidationAttribute, which means we can create custom validators for our types. Let's create a more appropriate validation for our Currency attribute:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace SampleAPI.Requests
{
public class CurrencyAttribute : ValidationAttribute
{
private readonly IList<string> _acceptedCurrencyCodes =
new List<string>{
"EUR",
"USD",
"GBP"
};
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
return _acceptedCurrencyCodes.Any(c => c == value.ToString()) ?
ValidationResult.Success
: new ValidationResult($"{validationContext.MemberName} is
not an accepted currency");
}
}
}
The preceding implementation matches the request model currency with the list of _acceptedCurrencyCodes. If the match is successful, it returns ValidationResult.Success; otherwise, it returns a new validation result with a validation message. The MemberName attribute provides the name of the property that is associated with the custom validation attribute. Creating a custom validation attribute can be useful when we implement a more complex validation that involves third-party services or aggregate operations on the subject of the validation.