jQuery 用 0 验证所需的方法和文本框
我有一个包含两个部分的表格。每个部分都通过其自己的单选按钮展开,因此一次只有一个可见部分。我使用 ASP.NET MVC HtmlHelper 生成如下所示的字段:
<label for="type-permanent" class="radio active">
<input type="radio" name="Type" value="Type1" id="type1" /> Label1
</label>
<%= Html.TextBox("Field1", Model.IntProperty1) %>
<label for="type-permanent" class="radio active">
<input type="radio" name="Type" value="Type2" id="type2" /> Label2
</label>
<%= Html.TextBox("Field2", Model.IntProperty2) %>
我还有两个函数,以便我可以确定哪个部分处于活动状态:
function isType1() { return $("#type1").attr("checked"); }
function isType2() { return $("#type2").attr("checked"); }
最后,我设置了以下验证方法:
Field1: {
required: isType1,
min: 1
},
Field2: {
required: isType2,
min: 1
}
现在,重点是,如果我将空模型传递给视图,两个字段都设置为 0(默认为 int)。现在,如果用户填写某些字段并尝试提交表单,则会出现验证错误,因为即使其他部分中的字段不是必需的,但它的值 - 0,这是不正确的,因为它必须大于 1除了在提交表单之前清除隐藏部分中的字段之外,如何克服这个问题?
更新。我想我需要某种条件验证方法。
I've got a form with two sections. Each section expands by its own radio button, so there's only one visible section at a time. And I use ASP.NET MVC HtmlHelper to generate fields like so:
<label for="type-permanent" class="radio active">
<input type="radio" name="Type" value="Type1" id="type1" /> Label1
</label>
<%= Html.TextBox("Field1", Model.IntProperty1) %>
<label for="type-permanent" class="radio active">
<input type="radio" name="Type" value="Type2" id="type2" /> Label2
</label>
<%= Html.TextBox("Field2", Model.IntProperty2) %>
I also have two functions so that I could determine, which section is active:
function isType1() { return $("#type1").attr("checked"); }
function isType2() { return $("#type2").attr("checked"); }
Finally, I've got the followind validation methods set up:
Field1: {
required: isType1,
min: 1
},
Field2: {
required: isType2,
min: 1
}
Now, the point is that if I pass empty model to the view, both fields are set to 0 (default for int). Now if the user fills some fields and tries to submit the form, there is validation error, because even though the field in other section is not required, but it has the value - 0, which is not correct since it must be more that 1. How can I overcome this except clearing fields in hidden sections before form submission?
UPDATE. I guess I need some kind of conditional validation method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您可以构建它,则所需的方法需要回调,因此也许您可以通过以下方式将零空检查构建到所需的验证器中: http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-callback
HTH。
If you can build it in, the required method takes a callback, so maybe you can build in the zero null check into the required validator via: http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-callback
HTH.