Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Asp.net MVC to validate a list property has a minimum number of items (count=N)?

I have a view model that has a property that looks like this

Property SelectedGroups() as List(of string)

In the view I have something like this

<table>
    <tr>
        <th>Description</th>
    </tr>
    <tr>
        <td>
            <input type="hidden" name="SelectedGroups" value="one" />
            description one
        </td>
    </tr>
    <tr>
        <td>
            <input type="hidden" name="SelectedGroups" value="two" />
            description two
        </td>
    </tr>
    <tr>
        <td>
            <input type="hidden" name="SelectedGroups" value="three" />
            description three
        </td>
    </tr>
</table>

The table rows are added and removed with jquery. Is there a way to create a validation attribute on SelectedGroups property that will require a minimum number of items for the list? This can be done with javascript but I would like it to work with

<% Html.EnableClientValidation()%>
<%: Html.ValidationSummary(False)%>
like image 351
Randall Hoffpauir Avatar asked Nov 05 '22 11:11

Randall Hoffpauir


1 Answers

You would have to write a custom validator. The built-in validators aren't that sophisticated.

ScottGu has written a good article on custom validators: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

like image 159
Dave Swersky Avatar answered Nov 15 '22 07:11

Dave Swersky