开发者

validating input fields that aren't part of the model

开发者 https://www.devze.com 2023-04-11 16:58 出处:网络
I\'ve read about how to get validation of my MVC Model working.It\'s pretty cool. But I need to validate a strictly UI situation, that doesn\'t relate to the model.开发者_开发技巧Specifically, I need

I've read about how to get validation of my MVC Model working. It's pretty cool.

But I need to validate a strictly UI situation, that doesn't relate to the model. 开发者_开发技巧Specifically, I need to check that the user clicked one of several checkboxes before clicking a link. Let me stress, again, that the checkboxes don't represent model data: they're strictly for View and Controller purposes.

In the WebForms world, I'd just stick in a RequiredFieldValidator. What's the equivalent for a field that DOESN'T represent a field on a model?


You will need to do some custom model binding to check the request object and act accordingly (adding modelstate errors, etc...) Here is a post related to custom model binding that should be beneficial.

ASP.Net MVC Custom Model Binding explanation

Once in the custom model binder you can add code in the CreateModel method similar to this:

Dim request As HttpRequestBase = controllerContext.HttpContext.Request
If Not request.Form.AllKeys.Contains("YourCheckBoxName") Then
     bindingContext.ModelState.AddModelError("AnError", "You must check the box first")
End If


You can use jquery validation to inject validation rules into the validationset.


Quick and dirty solution using a css class name to check if one of the boxes have been checked.

<input type="checkbox" value="1" name="something" class="boxGroupName" /> Check1
<input type="checkbox" value="2" name="another" class="boxGroupName" /> Check1
<input type="checkbox" value="3" name="third" class="boxGroupName" /> Check1

<input type="submit" id="buttonId" />    

<script type="text/javascript">
$(function() {
    $('#buttonId').click(function() {
        if ($('.boxGroupName:checked').length == 0) {
            alert('Check some boxes, ehh?');
            return false;
        }
        return true;
    });
});
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号