jQuery验证与提交处理程序 [英] jQuery validation with submit handler

查看:78
本文介绍了jQuery验证与提交处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery验证插件的validate方法设置了表单验证,并且有一个提交处理程序可以修改输入元素的值(我使用YUI编辑器,并且需要saveHTML()调用才能将iframe的内容复制到textarea元素. ).提交表单时,我希望验证程序在执行我的提交处理程序之后对表单进行验证.但是,如果在validate调用之后注册了它,它就不会执行我的提交处理程序.

I setup the form validation using jQuery validation plug-in's validate method and I have a submit handler that modifies the input element's value (I use YUI editor and it needs saveHTML() call to copy the iframe's content to the textarea element.). When submitting the form, I want the validator to validate the form after executing my submit handler. But it doesn't execute my submit handler if it is registered after the validate call.

例如,

<form id="form1" action="/test">
    <input type="text" name="txt1" id="txt1" />
    <input type="submit" value="submit" />

$(document).ready(function() {
    $("#form1").submit(function() {
        $("#txt1").val("123456");
    });

    $("#form1").validate({
        rules: {
            txt1: {
                maxlength: 5
            }
        }
    });
});

表单在我的提交处理程序之后经过验证,因此提交被取消.

The form is validated after my submit handler so submit is canceled.

$(document).ready(function() {
    $("#form1").validate({
        rules: {
            txt1: {
                maxlength: 5
            }
        }
    });

    $("#form1").submit(function() {
        $("#txt1").val("123456");
    });
});

但是,如果我更改顺序,则会在提交处理程序之前验证表单.

However if I change the order the form is validated before my submit handler.

推荐答案

您可以使用 beforeSubmit 回调以设置值:

You could use the beforeSubmit callback to set values:

$(function() {
    $('#form1').validate({
        rules: {
            txt1: { maxlength: 5 }
        },
        beforeSubmit: function(arr, $form, options) {
            $('#txt1').val('123456');
            return true;
        }
    });
});

这篇关于jQuery验证与提交处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆