ASP.net MVC Validation Hook

末鹿安然 提交于 2019-12-03 08:42:54

问题


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.


回答1:


You can use the invalidHandler, I believe that is in jquery validation.

invalidHandler Callback
Callback for custom code when an invalid form is submitted. Called with a event object as the first argument, and the validator as the second.




回答2:


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!

$(document).ready(function() {
    $('#myform').bind('invalid-form.validate',function(){
        alert('invalid form!');
    });
});

to give your form an id use:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myform" })) {
} 

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.

$(document).ready(function() {
    var existingValdiation = $("#myform").validate();
    //the settings property corresponds to the options parameter
    existingValdiation.settings.invalidHandler = function (form) {
        alert('invalid form!');
    };
    // not recommended:
    // re-init would bind settings.invalidHandler to 'invalid-form.validate'
    // existingValdiation.init();
});


来源:https://stackoverflow.com/questions/7651576/asp-net-mvc-validation-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!