-2

我使用“jquery-validation-1.11.1 插件”来检查注册表单的数据验证。它是一个很好用的插件。完整的代码在这里。

<html>
<head>
    <title>Data validation with jquery plug-in</title>
    <style>
        label{
            display:block;
            color: #555;

            margin-left:500px;
        }
        label.error{
            color: #900;
            font-style: Italic;
        }
        input{

            margin-left:500px;
        }
        textarea{
            margin-left:500px;
        }
    </style>
</head>

<body>
    <form id="comment" action="">
        <p>
            <label for="cname">Name(required, at least 2 characters)</label>
            <input id="cname" name="name">
        </p>
        <p>
            <label for="cemail">Name(required)</label>
            <input id="cemail" name="email" type="email">
        </p>
        <p>
            <label for="curl">URL(optional)</label>
            <input id="curl" name="url" type="url">
        </p>
        <p>
            <label for="comment">Your comment(required)</label>
            <textarea id="ccomment" name="comment"></textarea>
        </p>
        <p>
            <input class="submit" type="submit" value="submit">
        </p>
        <p>
            <input type="submit" value="Click">
        </p>
    </form>

    <script src="jquery.js"></script>
    <script src="jquery.validate.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#comment").validate({
                rules:{
                    name:{
                        "required":true,
                        "min":2
                    },
                    email:{
                        "required":true,
                        "email":true
                    },
                    comment:{
                        "required":true
                    }
                }

            });
        });
    </script>
</body>

我只想在单击“提交按钮”时检查验证。但现在我的问题是当我单击任何按钮时,进行数据验证。我该如何解决?

4

1 回答 1

0

尝试这个,

$('#myform').validate({
    rules:{
         name:{
             "required":true,
             "min":2
         },
         email:{
             "required":true,
             "email":true
         },
         comment:{
             "required":true
         }
    },
    submitHandler: function (form) { // for demo
        alert('form submitted');
        return false;
    }
});

$('#register').on('click', function () {
    $(this).closest('form').submit();
});
$('#home-page-submit').on('click', function () {
    // home page called
    alert('form cancelled');
    location.href='home.html';
    return false;
});

换个submit buttons喜欢,

    <p>
        <input class="submit" type="submit" value="submit" id="register">
    </p>
    <p>
        <input type="button" value="Click" id="home-page-submit">
    </p>
 </form>

另外你为什么要让你2 submit buttons可以创建一个simple button喜欢home-page

<input type="button" value="Go to home page" 
                 onclick="window.location.href='home.html'" />
于 2013-09-19T07:59:41.210 回答