jquery - asp.net Core 2.1 MVC 验证器不工作
问题描述
我有以下页面:
@model LogonModel
<div class="login-modal modal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Welcome</h5>
</div>
<div class="modal-body">
@if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger">
@foreach (var modelState in ViewData.ModelState)
{
<ul><li>@Html.ValidationMessage(modelState.Key, modelState.Value)</li></ul>
}
</div>
}
<div class="row">
<div class="col-md-12">
<p>Don't have an account? <a href="#">Contact us now.</a></p>
<form asp-action="Login" class="login-form">
<div asp-validation-summary="ModelOnly" class="validation-summary text-danger"></div>
<div class="form-group">
<label asp-for="EmailAddress" class="control-label">Email Address</label>
<input asp-for="EmailAddress" class="form-control" />
<span asp-validation-for="EmailAddress" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input type="password" asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Sign in" class="btn btn-default login-submit" />
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" asp-for="RememberUser">
<label class="form-check-label" asp-for="RememberUser">Remember my account details</label>
</div>
<div class="form-group">
<a href="#">Login using a subscription ID</a><br />
<a href="#">Forgot your password?</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
最初,发给控制器的帖子只是在提交按钮上,验证器工作。即省略电子邮件,验证器将显示错误消息。出于其他原因。当我按下提交按钮时,我在转到我的控制器之前调用一个 jQuery 函数,在我的 javascript 中,我做的第一件事是:
var loginForm = $(".login-form");
if (loginForm.valid()) {…..
这似乎不起作用,因为即使我关闭电子邮件,我的 javascript 也会被调用,它仍然会通过我的“if”语句中的代码。
我需要做什么才能让验证器再次工作?
解决方案
jQuery Validation 仅在输入被聚焦/修改或实际提交表单时触发(您的代码在此之前运行)。在任何一种情况下,该valid
方法仅报告已触发验证的输入的状态。换句话说,true
即使所需输入为空(如果尚未验证),它也有可能返回。
总而言之,您首先需要调用validate
来触发完整的表单验证。
loginForm.validate();
if (loginForm.valid()) {
...
}
推荐阅读
- r - ggplot:如何在不覆盖设置比例的情况下使用 scale_fill_discrete 并更改颜色
- python - 使用 Numpy 转置使用 2D 查询窗口迭代 3D 数组
- actor - 为什么 Actor Model 中的 Actor 可以有多个地址
- c# - 如何使用硒 C# 按像素比较两个图像
- angular - 使用 Angular 实现 OAuth2 身份验证
- javascript - 如何在 JavaScript 中的两组函数之间切换
- java - EurekaServer com.netflix.discovery.shared.transport.TransportException:无法在 Docker 上的任何已知服务器上执行请求
- scala - CSV 数据未正确加载为 Parquet 使用 Spark
- python - 在函数中引发异常
- excel - VBA关闭任何打开的excel文件和excel应用程序