views:

32

answers:

2

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?

+2  A: 

You extend ValidationAttribute as shown in this article. ValidationAttribute has a method IsValid() which you can override to indicate the model's validity.

Alex
+1 to you for not getting a vote, even though you beat me by 30 seconds. :)
RPM1984
Hehe, thanks. Your answer was better - people don't like to read :D
Alex
I didn't notice you were first. But yea.. Copy + Pasting is way easier. +1
Blankasaurus
+2  A: 

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; }
RPM1984
Awesome thanks!
Blankasaurus