This class validates that a name contains only letters and optionally spaces, hyphens and apostrophes.
public class NameAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null) return ValidationResult.Success;
string name = value.ToString();
var regex = new Regex(@"^[a-zA-Z]+(?:['-][a-zA-Z\s*]+)*$");
return regex.IsMatch(name)
? ValidationResult.Success
: new ValidationResult($"The name '{name}' is invalid, it should consist of only letters, and optionally spaces, apostrophes and/or hyphens.");
}
}
One thing I wasn't sure on was the null check at the start, we've got the Required
attribute if something is required and I don't want the validation to occur if the value is null. Is this an appropriate way of handling it?