使用jQuery验证进行表单验证

时间:2013-05-22 07:23:09

标签: jquery jquery-plugins

我在mvc4网站上有反馈表,我想对我的表单进行验证 我尝试使用jQuery Validation
我添加了jQuery库和<script src="/Scripts/jquery.validate.min.js"></script>
然后我写了(一个字段试试)

     <script>
      $(function () {
        $("#feedback-form").validate();

        $("#feedback-form").validate({
            rules: {
                Name: {
                    required: true,
                    minlength: 2
                },
            },
            messages: {
                Name: {
                    required: "Please enter a username",
                    minlength: "Your username must consist of at least 2 characters"
                },
            },
        });
    });
</script>

以我的形式

  @using (Html.BeginForm("Feedback", "Home", FormMethod.Post, new { id = "feedback-form" }))
    {
 <!-- Name -->
             @Html.TextBoxFor(model => model.Name, null, new { @class = "text-field" })
             <a href="#" class="link1" id="submit-button" onclick="document.getElementById('feedback-form').submit()"><em><b>Send</b></em></a>
}

它没有显示浏览器控制台中的任何错误,但验证不起作用。例如,当我按空字段发送按钮时,我什么也没收到,没有收到任何消息 怎么了?

3 个答案:

答案 0 :(得分:0)

删除$("#feedback-form").validate();,它应该可以正常工作。

答案 1 :(得分:0)

我建议您不要尝试验证文档何时准备好,而不是尝试提交表单,并且无需使用两种验证方法并删除您拥有的额外,逗号在验证中:

$(function () {
    $("#feedback-form").on('submit', function(){
      $(this).validate({
        rules: {
            Name: {
                required: true,
                minlength: 2
            }  // <-------------------------removed comma here
        },
        messages: {
            Name: {
                required: "Please enter a username",
                minlength: "Your username must consist of at least 2 characters"
            }  // <-------------------------removed comma here
        }      // <-------------------------removed comma here
     });
   });
});

答案 2 :(得分:0)

submitHandler: function(form) {
         form.submit();
          }

并删除

 $("#feedback-form").validate();

并删除,

 Name: {

        } , <--- here you add "," for 1 more rule or message