简体   繁体   中英

Form Validation using jQuery Validation

I have feedback form on my mvc4 site and I'd like to make validation for my form.
I try to use jQuery Validation
I added jQuery library and <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(); 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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