简体   繁体   English

使用jQuery验证的表单验证

[英]Form Validation using jQuery Validation

I have feedback form on my mvc4 site and I'd like to make validation for my form. 我在mvc4网站上有反馈表,我想对我的表单进行验证。
I try to use jQuery Validation 我尝试使用jQuery验证
I added jQuery library and <script src="/Scripts/jquery.validate.min.js"></script> 我添加了jQuery库和<script src="/Scripts/jquery.validate.min.js"></script>
Then I wrote (for one field to try) 然后我写了(供一个领域尝试)

     <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>

and in my form 并以我的形式

  @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>
}

It doesnt show any mistakes in browser console, but validation doesnt work. 它在浏览器控制台中没有显示任何错误,但是验证不起作用。 When I push Send-button with empty field for example, I receive nothing, no messages. 例如,当我按下带有空白字段的发送按钮时,我什么也没有收到,也没有消息。
What's wrong? 怎么了?

Remove $("#feedback-form").validate(); 删除$("#feedback-form").validate(); and it should work fine. 它应该可以正常工作。

What i would suggest you is do not try to validate when doc is ready instead you can try on submit of the form and there is no need to put two methods of validate and remove the extra , commas you have in your validation: 我建议你的是不要试图验证文档时准备好,而不是你可以尝试在表格的提交,也没有必要把验证两种方法,并删除多余的,逗号你在你的验证有:

$(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
     });
   });
});
submitHandler: function(form) {
         form.submit();
          }

and Remove 和删除

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

and Remove , 然后删除

 Name: {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM