无法在jquery中首次单击提交表单并进行验证

时间:2014-07-07 04:52:46

标签: jquery jquery-validate form-submit

我正在使用验证开发一个简单的登录表单,一切正常,但它不会在第一次点击时触发,这是我的代码JS文件:

$("form#login-form").submit(function(e){

e.preventDefault();    

//Form Validation goes here....

//Save Form Data........
$('form#login-form').validate({ // initialize the plugin
    rules: {
        userName: "required",
        password: {
            required: true,
            minlength: 5
        },
        agree: "required"
    },

    // Specify the validation error messages
    messages: {
        userName: "Please enter a user name",
        password: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long"
        },
        email: "Please enter a valid email address",
        agree: "Please accept our policy"
    },

    submitHandler: function (form) {
        $('#spinner').css('visibility', 'visible');
        $.ajax({
            cache: false,
            url : 'api/Values/GetName',
            type: "POST",
            dataType : "json",
            data : data,
            context : Form,
            success: function (callback) {
                $.each(callback, function (key, val) {
                    if (val === 'True') {
                        window.location.href = "Templates/internetSales.html";
                    }
                    else {
                        $('#fail').css('visibility', 'visible');
                    }

                });


                $('#spinner').css('visibility', 'hidden');
            },
            error : function(){
                $(this).html("Server Error!");
            }
        });
    }

});

      }                   );

html代码在这里:

<form id="login-form" novalidate="novalidate">
        <input type="text" name="userName" id="userName" placeholder="UserName" />
        <input type="password" name="password" placeholder="Password" />
        <input type="submit" id="loginSubmit"value="Log in" />
        <p id="fail" class="fail">Login failed try again!</p>
    </form>

我不知道在调试器中它进入调试点以在第一次点击时验证功能但没有任何反应,我尝试了多种方法,但确实没有帮助。请提供我出错的地方。

Demo Fiddle

1 个答案:

答案 0 :(得分:2)

宾果,你不需要

$("form#login-form").submit(function(e){        
e.preventDefault();
});

工作小提琴fiddle