user3428422
user3428422

Reputation: 4560

Data annotation validation for an invalid string

The scenario is this:

I have a list of countries in a dropdown box and have a select attribute called "Not Found" I had to include this as this was a text field so there is a lot of rubbish!

So when a user creates a from lets say, if they choose the "Not Found" option, I want an error to say "select valid country" pretty easy...

But I am having trouble finding the correct annotation

    [???(ErrorMessage = "Select a valid country.")]
    public string Country
    {
       get 
       set
    }

But what attribute do I need to put when the ?s are?

Thanks

Upvotes: 0

Views: 611

Answers (2)

Big Daddy
Big Daddy

Reputation: 5224

I think you want to create a custom attribute. Something like this:

class YourValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        // Do your validation check....and return a ValidationResult
            return ValidationResult.Success;
        }
    }

Then annotate your class with it:

[YourValidationAttribute]
    public string Country
    {
       get 
       set
    }

See this too: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute%28v=vs.110%29.aspx

Upvotes: 1

Related Questions