JQuery验证未验证

时间:2012-06-25 16:27:19

标签: jquery jquery-plugins jquery-validate

我正在尝试使用JQuery验证器插件来验证rails应用程序,但它既没有抛出任何错误也没有验证任何内容。我不知道我的代码还有什么问题 - 任何帮助都会受到赞赏!

$(document).ready(function() {
$(".theform").validate({
    rules: {
        name: {
            required:true,
            minlength:2,
            maxlength:50
        },
        email: {
            required: true,
            email: true,
            minlength:2,
            maxlength:50
        },
        phone_number: {
            required: true,
            phoneUS: true,
            minlength:9,
            maxlength:20
        }
    },
    messages: {
        name: {
            required: "Please provide your name",
            minlength: "Too few characters!",
            maxlength: "Too many characters!"
        },
        email: {
            required: "Please provide your email",
            email: "Your email address must be in the format of name@domain.com",
            minlength: "Too few characters!",
            maxlength: "Too many characters!"
        },
        phone_number: {
            required: "Please provide your phone number",
            phoneUS: "Please provide a valid US phone number",
            minlength: "Too few characters!",
            maxlength: "Too many characters!"
        }
    }
});
$("input#ajax").click(function() {
    $.ajax({
        type: "POST",
        url: "/create_user",
        data: {name: $('#name').val(), email: $('#email').val(), number: $('#phone_number').val(), ajax:"true"},
        success: function(msg){
            //console.log(msg.name);
            $("div#n").html(msg.name);
            $("div#e").html(msg.email);
            $("div#p").html(msg.phone_number);
        }
    });
});
});
编辑:这是我要验证的表格:

<div id="theform">
<form name="form" action="create" method="post">

    Name: <input type="text" name="name" id="name"/><br/>
    Email: <input type="text" name="email" id="email"/><br/>
    Phone Number: <input type="text" name="phone_number" id="phone_number" /><br/>
    <input type="submit" value="Normal Submit" id="normal">
    <input type="button" value="Ajax Submit" id="ajax">

</form>
</div>

1 个答案:

答案 0 :(得分:1)

你的选择器错了:

$(".theform").validate({ ... });

选择所有元素theform的元素,这些元素都没有。您需要选择form元素本身:

$("#theform > form").validate({ ... });

$("form[name='form']").validate({ ... });

示例: http://jsfiddle.net/nQq6t/