如何在没有数据注释的情况下使字段为必填项 [英] How to make a field required without data annotation

查看:88
本文介绍了如何在没有数据注释的情况下使字段为必填项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MvcContrib网格在页面上显示表格.我正在使用自定义列在表格上产生一个复选框,以便用户可以选择多行并提交表单.

I am using the MvcContrib Grid to display a table on the page. I am using a custom column to produce a checkbox on the table so that the user can select multiple rows and submit the form.

除非已至少选中一个复选框,否则我不希望提交表单.我可以自己编写该Javascript来强制执行验证,但是我想知道如何将其与MVC3随附的不引人注目的库配合使用.

I don't want the form to submit unless at least one checkbox has been selected. I could easily write this Javascript myself to enforce the validation, but I wanted to know how I could fit it in with the unobtrusive library supplied with MVC3.

我想我只需要为输入设置适当的类和属性,然后页面上的脚本(validate和validate.unobtrusive)应该将它们选中并标记为需要验证,但是我无法到目前为止,以获得正确的组合.

I imagine I just need to set my inputs with the proper classes and attributes and then the scripts (validate and validate.unobtrusive) on the page should pick them up and mark them as needing validation, but I haven't been able to get the right combination thus far.

这是我当前正在生成的输入:

Here is the input that I am currently generating:

<input type="checkbox" 
       name="foo" 
       value="@item.foo" 
       class="input-validation-error" 
       data-val-required="Please select an option." 
       data-val="true" />

推荐答案

尝试在项目上设置data-val属性,然后必须告诉jQuery您有新内容,可通过类似以下方式重新解析表单:

Try setting the data-val attributes on the item, then you have to tell jQuery you have new content to re-parse the form via something like:


 $.validator.unobtrusive.parse($('#yourForm'));

其中form当然是对form元素的引用.

where form is of course a reference to your form element.

也有一篇很棒的文章,jQuery有一些您可以调用的内部适配器: 来自 http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

There is also this great posting and jQuery has a few internal adapters you can call: from http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2


jQuery.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty", "mynotequaltofunction")

这篇关于如何在没有数据注释的情况下使字段为必填项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆