Валидация формы с использованием jQuery Validation

237
12 декабря 2016, 10:11

Делаю валидацию полей формы при помощи jQuery Validation.

Подключаю библиотеку jQuery, подключаю скрипт jquery.validate.min.js Вот форма

<form action="" class="ajax_form" id="commentForm">
            <label for="name_popup">Ваше имя</label>
            <input type="text" name="name" id="name_popup" required>
            <label for="phone_popup">Телефон</label>
            <input type="text" name="phone" id="phone_popup" required>
            <label for="mail_popup">E-mail</label>
            <input type="email" name="mail" id="mail_popup" required>
            <input type="submit" class="button" value="Отправить заявку">
            <input type="hidden" name="form_type" value="">
        </form>
<script> $("#commentForm").validate();
</script>

Также есть скрипт для отправки форм:

 $('.ajax_form').submit(function() {
    form = $(this);
    var str = $(this).serialize();
    $.ajax({
        type: "POST",
        url: "../send.php",
        data: str,
        success: function(msg) {
          var yaCounter28330736 = new Ya.Metrika({id: 28330736});
          yaCounter28330736.reachGoal('order');
          height = $(form).height();
          $(form).hide();
          $(form).after('<div class="after" style="padding:25px;height:'+height+';text-align:center;">'+msg+'</div>');
          setTimeout(function() {
            $('#popup, #splash').fadeOut(1000);
            $(form).fadeIn();
            $(form).delay(1000).next('.after').remove();
          },4000);
          console.log(msg);
        }
    });
    $(this).find(".button").attr('disabled','disabled');
    $(this).find(".big_button").attr('disabled','disabled');
    return false;
});

Как их объединить, чтобы при нажатии "отправить" сначала была проверка на валидацию, а потом уже отправка формы?

Answer 1
$(".ajax_form").validate({
   onkeyup: false,
   rules: {
       name: {required: true},
       phone: {required: true},
       mail: {required: true},
   },
   messages: {
       name: {required: 'blablabla'},
       phone: {required: 'asdasd'},
       mail: {required: 'egaweawe'},
   },
   errorPlacement: function(error,element) {return true;},
   invalidHandler: function(event, validator) {alert(validator.errorList[0].message);},
   submitHandler: function(form) {
        str form.serialize();
        $.ajax({
            type: "POST",
            url: "../send.php",
            data: str,
            success: function(msg) {
                var yaCounter28330736 = new Ya.Metrika({id: 28330736});
                yaCounter28330736.reachGoal('order');
                height = $(form).height();
                form.hide();
                form.after('<div class="after" style="padding:25px;height:'+height+';text-align:center;">'+msg+'</div>');
                setTimeout(function() {
                    $('#popup, #splash').fadeOut(1000);
                    form.fadeIn();
                    form.delay(1000).next('.after').remove();
                },4000);
                console.log(msg);
           }
      });
   }
});
READ ALSO
Циклическая работа

Циклическая работа

Доброго времени суток

192
Не всегда работает prop

Не всегда работает prop

Бывают случаи, когда prop не срабатываетПочему это происходит и как это исправить?

238
Перемещение элемента

Перемещение элемента

К примеру, есть такой код:

208
Jquery получить url и method  от ajax события

Jquery получить url и method от ajax события

Задача состоит в том, чтобы все post запросы, сделанные через ajax, уведомляли нужный мне скрипт о том, к какому url они обращались

200