Проверка jQuery onblur - PullRequest
       44

Проверка jQuery onblur

26 голосов
/ 07 января 2011

Я пытаюсь заставить валидацию jQuery работать на веб-странице, которую я создаю.У меня есть около 6 различных наборов полей, которые содержат детали страницы.Я использую это, поскольку я скрываю и показываю их, чтобы улучшить взаимодействие с пользователем.

У меня плагин работает так, как я хочу, когда я пытаюсь отправить страницу и всякий раз, когда я добавляю один символ (когда текстовое поле требуетили больше символов) однако я также хочу, чтобы проверка происходила onblur.Я хочу сразу же сообщить своим пользователям, если они не выполнили условие проверки, чтобы они могли исправить это немедленно и не возвращаться.

Может кто-нибудь сказать мне, что мне нужно сделать, яиспользуя плагин * http://bassistance.de/jquery-plugins/jquery-plugin-validation/.

Это код jQuery, который я написал до сих пор:

      $("#aspnetForm").validate({
            rules: {
            <%=txtFirstName.UniqueID %>:
                {
                    required: true,
                    minlength: 2
                }
                ,
                <%=txtSurname.UniqueID %>:
                {
                    required: true,
                    minlength: 2
                }
                ,
                <%=txtMobileNumber.UniqueID %>:
                {
                    required: true,
                    minlength: 8
                }
                ,
                <%=Email.UniqueID %>:
                {
                    required: true,
                    email: true
                }
                ,
                   <%=ddDay.UniqueID %>:
                {
                    required: true

                }
                ,
                   <%=ddMonth.UniqueID %>:
                {
                    required: true

                }
                ,
                   <%=ddYear.UniqueID %>:
                {
                    required: true

                }
                ,
                <%=txtHouseNumber.UniqueID %>:
                {
                    required: true,
                    minlength:1

                }
                ,
                <%=txtAddress1.UniqueID %>:
                {
                    required: true,
                    minlength:5
                }
                ,
                <%=txtCity.UniqueID %>:
                {
                    required: true,
                    minlength:2
                }
                ,
                <%=txtSuburb.UniqueID %>:
                {
                    required: true,
                    minlength:2
                }
                ,
                <%=txtPostCode.UniqueID %>:
                {
                    required: true,
                    minlength:4,
                    maxlength:4
                }

                 ,
                <%=UserName.UniqueID %>:
                {
                    required: true,
                    minlength:4

                }
                ,
                <%=Password.UniqueID %>:
                {
                    required: true,
                    minlength:4

                }
                ,
                 <%=ConfirmPassword.UniqueID %>:
                {
                   equalTo: "ctl00$ctl00$cpMain$cpLeft$Password"

                }
                  ,
                <%=chkTerms.UniqueID %>:
                {
                    required: true


                }

            },
            messages: {
                <%=txtFirstName.UniqueID %>:
            {
                required: "Please enter your firstname",
                minlength: "Minimum length is 2 characters"
            },
               <%=txtSurname.UniqueID %>:
            {
                required: "Please enter your lastname",
                minlength: "Minimum length is 2 characters"
            },
            <%=txtMobileNumber.UniqueID %>:
            {
                required: "Please enter your mobile",
                minlength: "Minimum length is 8 characters"
            }
            ,
            <%=ddDay.UniqueID %>:
            {
                required: "Please enter your date of birth"

            }
            ,
            <%=txtMobileNumber.UniqueID %>:
            {
                  required: "Please enter your date of birth"
            }
            ,
            <%=txtMobileNumber.UniqueID %>:
            {
                   required: "Please enter your date of birth"
            }
            ,
                  <%=Email.UniqueID %>: 
                  "Please enter a valid email"
            ,
            <%=txtHouseNumber.UniqueID %>:
            {
                   required: "Please enter your house number",
                   minlength:"Please add at least 1 character"
            }

             ,
            <%=txtAddress1.UniqueID %>:
            {
                   required: "Please enter your address",
                   minlength:"Please add at least 5 characters"
            }
            ,
            <%=txtCity.UniqueID %>:
            {
                   required: "Please enter your city",
                   minlength:"Please add at least 2 characters"
            }
            ,
            <%=txtSuburb.UniqueID %>:
            {
                   required: "Please enter your city",
                   minlength:"Please add at least 2 characters"
            }
             ,
            <%=txtPostCode.UniqueID %>:
            {
                   required: "Please enter your postcode",
                   minlength:"Please add the 4 required characters",
                   maxlength:"Only 4 characters are allowed"
            }
             ,
            <%=UserName.UniqueID %>:
            {
                   required: "Please enter your username",
                   minlength: "Please add the 4 required characters"

            }
             ,
            <%=Password.UniqueID %>:
            {
                   required: "Please enter your password",
                   minlength: "Please add the 4 required characters"

            }
             ,
            <%=ConfirmPassword.UniqueID %>:
            {
                  equalTo: "Passwords must match"
             }
            ,
            <%=chkTerms.UniqueID %>:
            {
                   required: "Please agree to the terms"


            }

           }


        });

Любые советы?

Ответы [ 6 ]

51 голосов
/ 23 июня 2011

Дайвер Дэн был прав

$('form').validate({
    onfocusout: function (element) {
        $(element).valid();
    },
    rules: {
        name: 'required',
        from: 'required'

    },
    messages: {
        name: 'Please enter your firstname',
        from: 'Please enter where are you from'
    }
});
12 голосов
/ 07 января 2011

Я не вижу ничего в документах, которые могли бы это сделать. Единственный способ, которым я могу думать, это сделать.

$('#field1, #field2, #field3').blur(function(){
    validator.validate()
});
7 голосов
/ 25 апреля 2013

Вы также можете использовать вызов элемента валидатора.

   $('form').validate({
        onfocusout: function(element) {
           this.element(element);
        },
        rules: {
            name: 'required',
            from: 'required'

        },
        messages: {
            name: 'Please enter your firstname',
            from: 'Please enter where are you from'
        }
    });
3 голосов
/ 25 августа 2014

Просто установите onkeyup = false

$('form').validate({
    rules: {
        name: 'required',
        from: 'required'

    },
      onkeyup: false
       ,
    messages: {
        name: 'Please enter your firstname',
        from: 'Please enter where are you from'
    }
});
0 голосов
/ 20 июня 2018

попробуй:

onkeyup: function (element, event) {

 $(element).valid();
 // your code
}
0 голосов
/ 04 мая 2017

Код Тиа не будет запускать проверку onkeyup, но при размытии "потерян focus "проверка будет запущена, как и когда пользователь начнет редактировать поле, сообщение проверки исчезнет. Найдите более интересную другую настройку по этой ссылке: https://jqueryvalidation.org/category/plugin/

$('#frm').validate({
            onkeyup: false,
            focusCleanup: true
        });
...