ASP.net MVC 验证挂钩
我在 ASP.net MVC 3 中有以下视图:
@model Models.CreateProjectViewModel
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
@using( Html.BeginForm() ) {
@Html.TextBoxFor(m => m.ProjectName)
@Html.ValidationMessageFor(m => m.ProjectName)
<p>
<input type="submit" value="Save" />
</p>
}
我将不引人注目的 javascript 与 jQuery 和 Fluent Validation 框架一起使用。
当我单击“保存”按钮并且验证失败时,是否有一些事件我可以挂钩来调用一些自定义 JavaScript?
function validationFailed() {
// do something here only if validation failed
}
我如何与验证联系起来,以便当它失败时(并且仅当它失败时)我可以调用我的validationFailed()函数。
I have the following view in ASP.net MVC 3:
@model Models.CreateProjectViewModel
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
@using( Html.BeginForm() ) {
@Html.TextBoxFor(m => m.ProjectName)
@Html.ValidationMessageFor(m => m.ProjectName)
<p>
<input type="submit" value="Save" />
</p>
}
I am using unobtrusive javascript with jQuery and the Fluent Validation framework.
When I click the Save button and validation fails, is there some event I can hook into to call some custom javascript?
function validationFailed() {
// do something here only if validation failed
}
How would I tie into the validation so that when it failed (and only if it failed) I could call my validationFailed() function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 jQuery/Validation 文档所述,您可以使用 invalidHandler 在提交无效表单时做出反应。
但由于 MVC 不显眼的验证会实例化验证本身,因此您必须稍后挂钩此事件。
使用与 jQuery/Validation 完全相同的机制:您可以将代码绑定到表单元素自定义事件“invalid-form.validate”,该事件对应于 invalidHandler!
要为您的表单提供 id,请使用:
更新:获取现有验证对象的另一种方法是在表单上调用 validate()。如果此表单的验证器已创建,它将被返回:编辑:初始化发生后,更改
.settings.invalidHandler
对于绑定来说太晚了。因此,除非您重新初始化验证器,否则以下代码片段将不再起作用。As jQuery/Validation docs says, you could use invalidHandler to react when an invalid form is submitted.
But since MVC unobtrusive validation instantiates the Validation itself, you have to hook this event later.
Using exactly the same mechanism as the jQuery/Validation does: you could bind your code to the form elements custom event 'invalid-form.validate', witch corresponds to the invalidHandler!
to give your form an id use:
Update:An alternative way to get the existing validation object is calling validate() on the form. If a validator for this form was already created, it will be returned:Edit: after initialization occured, changing
.settings.invalidHandler
is too late for binding. So the following snippet will not work [anymore] unless you re-init the validator.您可以使用
invalidHandler
,我相信这是在jquery验证中。You can use the
invalidHandler
, I believe that is in jquery validation.