I have a question regarding the customized attribute trigger order of different model annotations in .NET. Please see below example:
public class DataModel
{
[Required]
[ValidName]
public string Name { get; set; }
}
So here we have two annotations, one is default Required and another is a customized one.
The latter one is like below:
public class ValidNameAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var name = value.ToString();
var nameIsLegal = new Regex("^[a-zA-Z0-9_-]*$").IsMatch(name);
if (name.Length > 50)
{
return new ValidationResult("The name should be less than 50 characters.");
}
if (!nameIsLegal)
{
return new ValidationResult("The name should be letters, numbers, hyphens, or underscores.");
}
return ValidationResult.Success;
}
}
And there is the problem with above implemention, var name = value.ToString(); will throw an exception when the value is null, and this seems odd and counter-intuitive to me. Since to my understanding, the Required annotation should prevent it from happening, but it won't.... So we have to add some logic like:
if (value == null)
{
return new ValidationResult("The name should be provided.");
}
So [Required] is totally useless in this case?
Thanks!
Here is an answer for similar issue, but it doesn't help. :(