MVC3 条件 JQuery 验证
我正在尝试使用 jQuery 验证器进行一些条件验证。
我有一个 javascript 向导,在进入下一步时调用验证方法:
var validator = $("form").validate();
var anyError = false;
step.find("input").each(function () {
if (!validator.element(this)) {
// validate every input
anyError = true;
}
});
if (anyError) {
return false;
}
当我在模型上有 [Required] 属性时,一切正常。
但是我有这种情况:
- 我有一个下拉菜单,可以选择:电子邮件或 Ftp
- 当选择电子邮件选项时,我想显示电子邮件地址字段并添加验证
- 当选择 Ftp 选项时,我不想验证电子邮件地址
这是电子邮件地址的 html 片段。
<div class="email-address" style="display: none;">
<label class="fullwidth" for="EmailAddress">Email Address</label>
@Html.TextBoxFor(m => m.EmailAddress, new { @class = "longtext" })
<div id="email-validation">
</div>
我已经尝试了各种方法,但下一个按钮验证例程始终认为该表单是有效的。例如。
$("form").validate({
errorLabelContainer: '#email-validation',
rules: {
EmailAddress: {
required: true
}
},
messages: {
EmailAddress: "Please enter an email address"
}
});
任何帮助表示赞赏。
I'm trying to do some conditional validation using the jQuery validator.
I have a wizard in javascript that calls the validate method when moving to the next step:
var validator = $("form").validate();
var anyError = false;
step.find("input").each(function () {
if (!validator.element(this)) {
// validate every input
anyError = true;
}
});
if (anyError) {
return false;
}
All works fine when I have a [Required] attribute on the model.
However I have this scenario:
- I have a drop down with a choice: Email or Ftp
- When the Email option is selected I want to show the email address field and add validation
- When the Ftp option is selected I don't want to validate the email address
Here's the html snippet for the email address.
<div class="email-address" style="display: none;">
<label class="fullwidth" for="EmailAddress">Email Address</label>
@Html.TextBoxFor(m => m.EmailAddress, new { @class = "longtext" })
<div id="email-validation">
</div>
I've tried all sorts but the next button validation routine always thinks the form is valid. For example.
$("form").validate({
errorLabelContainer: '#email-validation',
rules: {
EmailAddress: {
required: true
}
},
messages: {
EmailAddress: "Please enter an email address"
}
});
Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定,但我很确定您不能将标准 jquery 验证与 MVC3 客户端验证结合使用。您必须执行其中之一。
更具体地说,MCV3 客户端验证适应 jquery-validation 供其自身使用,这与独立使用 jquery-validation 相冲突。
I'm not certain, but i'm pretty sure you can't use standard jquery-validation in conjunction with MVC3 client-side validation.. You have to do one or the other.
To be more specific, MCV3 client-side validation adapts jquery-validation for it's own use, and this conflicts with using jquery-validation stand-alone.
我会利用
disabled
输入不参与验证的事实。添加服务器端所需的内容,但只需在选择 ftp 时禁用并隐藏 EmailAddress。I would use the fact that
disabled
inputs do not participate in validation. Add required for server side but just disable and hide EmailAddress when ftp is selected.