Darf Zon
Darf Zon

Reputation: 6378

How to create a custom validation in MVC4?

I realized that in MVC4 use validation attributes to perform this task. But know I'm dealing with a different situation.

Here is the model, in it I have a collection property Choices (this all the time has 5 elements) and CorectChoice where is the selected index from the collection.

public class MultipleChoiceQuestionTemplate : QuestionTemplate
{
    public MultipleChoiceQuestionTemplate() { ... }

    [DisplayName("Question")]
    public string QuestionText { get; set; }
    public List<string> Choices { get; set; }

    [DisplayName("Correct Choice")]
    public int CorrectChoice { get; set; }
}

And here is the view, watch the presentation.

enter image description here

    <div id="choices">
    @for (int i = 0; i < Model.Choices5.Count; i++) {
        <div class="choice-container" style="display: block;">
        @Html.TextBoxFor(model => model.Choices5[i])
        @Html.RadioButtonFor(model => model.CorrectChoice, i)
        </div>
    }   
    </div>

Note that the user can leave empty strings in the inputs (type="text"). I need to validate that the selected index (radiobuttons) should have a string.

How can I validate it before submit to the form?

Upvotes: 3

Views: 4645

Answers (2)

Adam Tuliper
Adam Tuliper

Reputation: 30152

Since you want this on the client side you would need IClientValidateable for the custom logic or write your own manual validation, not IvalidateableObject which is only server side. HOWEVER - the first thing to try is Darin's answer here which may get you away quite simply with proper placement of the validation error.

MVC Radio Button Lists are not grouped when using the HtmlHelper class

If that doesn't work another option to at least know about is IClientValidateable ASP.NET MVC implement custom validator use IClientValidatable

If Darin's solution above in the first link doesn't work for some reason I believe it should) You could actually get away here fairly simply in multiple ways

  1. Simply intercept the form post and query the radio buttons and ensure one is selected. Since you could in theory have multiple radio button types, you can use a selector to ensure its part of a form or contains a class type. If Darin's solution doesn't work let me know and I'll provide a solution on this one if you need help.

  2. Use unobtrusive validation on the radio buttons. Only the first one in the list though will get the errors. You'll have to workaround a little magic with css classes but the solution is here: ASP.NET MVC 3 unobtrusive validation and radio buttons

Upvotes: 1

Jorge
Jorge

Reputation: 18237

You must implement the Interface IValidatableObject check this article for can see an example http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvccustomvalidation_topic4

Upvotes: 0

Related Questions