-3

我想验证一个任何字段都不应该为空的表单。我不知道字段的名称。代码是:

 <form action="/addproductgroupinsert_fun/" method="post" name="SForm" onsubmit="return validateForm()">
    {% for id in ProductTypefeatureentryList %}
       <label for="{{id.Name}}">{{id.Name}}</label>
       <input id="{{id.Name}}" type="text"name="{{id.Name}}" />
    {% endfor %}

怎么能做到这一点?

4

3 回答 3

0

您可以考虑 HTML-5data-val-*属性并查看 jquery unobtrusive validation plugin。你的输入看起来像

 <form action="/addproductgroupinsert_fun/" method="post" name="SForm" onsubmit="return validateForm()">
    {% for id in ProductTypefeatureentryList %}
       <label for="{{id.Name}}" data-val-required='true'>{{id.Name}}</label>
       <input id="{{id.Name}}" type="text"name="{{id.Name}}" data-val-required='true' />
    {% endfor %}

data-val-required用于告诉不显眼的 js 需要 feild 的值。您在互联网上看到的大多数文章都会将不显眼的 js 与 asp.net mvc 链接起来,但它是一个客户端库,可以使用任何服务器端技术。此外,我还没有测试过代码,我认为还有一个属性可以指定错误消息,以防字段的值无效。

于 2012-10-23T14:11:16.533 回答
0

在您的模板中,添加一个类以根据需要标记它们。然后您可以使用该类验证所有元素:

{% for id in ProductTypefeatureentryList %}
   <label for="{{id.Name}}">{{id.Name}}</label>
   <input class="required" id="{{id.Name}}" type="text"name="{{id.Name}}" />
{% endfor %}

validateForm()

$('.required').each(function () {
    if (this.value === '') {
        // form is invalid
    }
});
于 2012-10-23T14:11:18.500 回答
-1

这贯穿您的输入列表:

$('input').each(function() {
   //Do your validation
});
于 2012-10-23T14:10:31.410 回答