我有一个非常简单的通讯订阅表格:
@using (Ajax.BeginForm("Register", "Home", new AjaxOptions
{
Confirm = "confirm?",
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "response"
}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div id="response">
<div class="form-group">
@Html.TextBoxFor(model => model.Email, new { @class = "form-control", @placeholder = "insert email" })
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="form-group">
<input type="submit" id="submit" value="subscribe" class="btn btn-default" />
</div>
</div>
}
电子邮件字段需要填写,并且是有效的电子邮件。 问题是,一旦我开始在文本框中键入内容,验证就会触发,并且弹出“电子邮件无效”消息。这很烦人。有没有办法在单击提交按钮时激活验证,而不是每个文本框都更改? 谢谢。
答案 0 :(得分:1)
如果您使用ValidationMessageFor,那么MVC将在您键入时立即触发。而是使用Jquery或javascript验证。
HTML:
@Html.TextBoxFor(model => model.Email, new { @class = "form-control", @placeholder = "insert email" })
<div id="emailerror" class="hide">The email is required</div>
JQuery的:
var pattern = /^([\w\-\.]+)@@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,3}))$/;
var email = $('#Email').val();
if (email == "") {
$('#emailerror').removeClass('hide');
$('#emailerror').addClass('error');
return false;
} else if (!pattern.test(email)) {
$('#emailerror').removeClass('hide');
$('#emailerror').addClass('error');
document.getElementById("emailerror").innerHTML = "The Email is not valid";
return false;
}
else {
$('#emailerror').addClass('hide');
$('#emailerror').removeClass('error');
return true;
}
CSS:
.hide {
display:none;
}
.error {
position: absolute;
margin-top:48px;
margin-left:-300px;
z-index: 1060;
max-width: 276px;
padding: 10px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 13px;
font-weight: 400;
line-height: 1.42857143;
text-align: left;
white-space: normal;
color: #fff;
background-color: #c14a4a;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 0px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
}
答案 1 :(得分:1)
作为替代方案,您可以更直接地将函数传递给onfocusout
的{{1}}和onkeyup
设置,以确定是否必须在这些事件中验证元素,就像这样:
jquery.validator
<强> SOURCE 强>