Jordan
Jordan

Reputation: 5465

Validating a List<string> in ASP.NET MVC 3

I have a "Contact Us" page where I have a list of questions and answers like so:

public List<string> Questions = new List<string>()
                                    {
                                        "What browser are you using?",
                                        "What version of the browser are you using?",
                                        "And so on and so forth..."
                                    };

public List<string> Answers { get; set; }

Then I'm adding these to the view like so:

           @foreach (var question in Model.Questions)
            {
                <dt>
                    <dd width="240" height="25">@Html.Label(question)</dd>

                    <dd width="240" height="80">
                        @Html.ValidationMessageFor(model => model.Answers[Model.Index])
                        @Html.TextAreaFor(model => model.Answers[Model.Index], new { @class = "uniform", @id = "text" })
                      </dd>
                </dt>
                Model.Index += 1;
            }

Before I go about writing a custom validator, is there a way I can validate each string in that list of answers similar to the way I would validate a string field?:

[StringLength(100)]

Thanks in advance!!

Upvotes: 0

Views: 1805

Answers (1)

Adam Tuliper
Adam Tuliper

Reputation: 30162

Your list of questions should be another model contained within your Contact Us page model so you can then assign those attributes to that model. This way you'll get the validation on each item.

Another alternative is simply to check the length in the controller code (no client validation here of course) and use ModelState.AddError() to manually add an error if your validation fails.

A third option (server side again) is to implement IValidateableObject in your model to manually check these values.

Upvotes: 2

Related Questions