1

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 Answers 2

4

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; }
Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.