I have a viewmodel that partially looks like this...
[Required]
public int Year { get; set; }
[Required]
[Range(1, 5000000)]
public int ModelID { get; set; }
[Required]
开发者_如何学运维public int ZipCode{ get; set;}
I want to add a custom validator attribute that checks a database to make sure the Zip is valid. Something like...
[Required]
[IsValidZipcode]
public int ZipCode{ get; set;}
I haven't been able to find a tutorial on the net - I don't think I know what to search for because this seems like it would be common.
How should I go about this?
Just create a class which inherits from the ValidationAttribute class, ovveriding the IsValid method:
public class IsValidZipCode: ValidationAttribute
{
public override bool IsValid(object value)
{
return db.ValidateSomething(value);
}
}
Then you're good to go:
[IsValidZipCode(ErrorMessage = "Not a valid zip code!")]
public int ZipCode { get; set; }
You extend ValidationAttribute
as shown in this article. ValidationAttribute
has a method IsValid() which you can override to indicate the model's validity.
精彩评论