可以JQuery.Validate插件prevent提交一个Ajax形式 [英] Can JQuery.Validate plugin prevent submission of an Ajax form

查看:153
本文介绍了可以JQuery.Validate插件prevent提交一个Ajax形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery插件的形式( http://malsup.com/jquery/form/ )来处理AJAX提交表单。我也有JQuery.Validate( http://docs.jquery.com/Plugins/Validation )插在我的客户端验证。

我所看到的是,当我期望它但它不会从停止提交表单验证失败。当我使用的是传统的形式(即非Ajax)验证失败prevented的形式提交所有....这是我期望的行为。

我知道,验证挂接正确的验证消息仍显示在AJAX提交发生后。

所以我我缺少的是preventing我想要的行为?下面的示例code ....

 <形式ID =searchForm方法=邮报行动=/用户/ GetDetails>
        <输入ID =用户名NAME =用户名类型=文字值=user.name/>
        <输入ID =提交名称=提交类型=提交值=搜索/>
< /形式GT;
< D​​IV ID =DetailsView控件>
< / DIV>

<脚本类型=文/ JavaScript的>
    VAR的选择= {
        目标:#detailsView
    };
    $('#searchForm)当作ajaxForm(选项)。

    $('#searchForm)。验证({
    规则:{
    用户名:{要求:真实}},
    消息:{
    用户名:{要求:用户名是必填字段。}}
    });
< / SCRIPT>
 

解决方案

您需要初始化当作ajaxForm()时,增加一个回调函数用于与beforeSubmit事件:

  VAR选项= {
        beforeSubmit:函数(){
            返回$('#searchForm)验证()的形式()。;
        },
        目标:#detailsView
    };
 

现在它知道要检查验证结果前,将提交页面。

I am using the JQuery form plugin (http://malsup.com/jquery/form/) to handle the ajax submission of a form. I also have JQuery.Validate (http://docs.jquery.com/Plugins/Validation) plugged in for my client side validation.

What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour.

I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened.

So what I am I missing that is preventing my desired behaviour? Sample code below....

<form id="searchForm" method="post" action="/User/GetDetails">
        <input id="username" name="username" type="text" value="user.name" />  
        <input id="submit" name="submit" type="submit" value="Search" />   
</form>
<div id="detailsView">
</div>  

<script type="text/javascript">
    var options = {
        target: '#detailsView'
    };
    $('#searchForm').ajaxForm(options);

    $('#searchForm').validate({
    rules: {
    username: {required:true}},
    messages: {
    username: {required:"Username is a required field."}}
    });
</script>

解决方案

You need to add a callback function for use with the beforeSubmit event when initializing the ajaxForm():

var options = {
        beforeSubmit: function() {
            return $('#searchForm').validate().form();
        },
        target: '#detailsView'
    };

Now it knows to check the result of the validation before it will submit the page.

这篇关于可以JQuery.Validate插件prevent提交一个Ajax形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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