ASP.net MVC Validation Hook

后端 未结 2 1630
慢半拍i
慢半拍i 2021-02-04 04:56

I have the following view in ASP.net MVC 3:

@model Models.CreateProjectViewModel



        
2条回答
  •  花落未央
    2021-02-04 05:50

    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();
    });
    

提交回复
热议问题