S
S
struggler2020-04-17 18:10:49
css
struggler, 2020-04-17 18:10:49

How to remove classes after jQuery contact form validation?

Hello, please help me with a problem!
Is there a feedback form on jQuery & Jquery Validation?
When the form changes, highlighting appears, that is, styles for error & valid classes are written in CSS, which are added by Jquery Validation. True, after removing all characters from the field, the error & valid classes do not disappear.
How can this be fixed? After sending, they are deleted, everything is OK!
5e99c69eacdf0480410736.jpeg

$(document).ready(function() {
        $('[data-submit]').on('click', function(e) {
            e.preventDefault();
            $(this).parent('form').submit();
        })
        $.validator.addMethod(
            "regex",
            function(value, element, regexp) {
                var re = new RegExp(regexp);
                return this.optional(element) || re.test(value);
            },
            "Please check your input."
    );

    // Функция валидации и вывода сообщений
    function valEl(el) {

        el.validate({
            rules: {
                tel: {
                    required: true,
                    regex: '^([\+]+)*[0-9\x20\x28\x29\-]{5,20}$'
                },
                name: {
                    required: true
                },
                email: {
                    required: true,
                    email: true
                }
            },
            messages: {
                tel: {
                    required: 'Поле обязательно для заполнения',
                    regex: 'Телефон может содержать символы + - ()'
                },
                name: {
                    required: 'Поле обязательно для заполнения',
                },
                email: {
                    required: 'Поле обязательно для заполнения',
                    email: 'Неверный формат E-mail'
                }
            },

            // Начинаем проверку id="" формы
            submitHandler: function(form) {
                $('#loader').fadeIn();
                var $form = $(form);
                var $formId = $(form).attr('id');
                switch ($formId) {
                    // Если у формы id="goToNewPage" - делаем:
                    case 'goToNewPage':
                        $.ajax({
                                type: 'POST',
                                url: $form.attr('action'),
                                data: $form.serialize(),
                            })
                            .always(function(response) {
                                //ссылка на страницу "спасибо" - редирект
                                location.href = 'https://';
                                //отправка целей в Я.Метрику и Google Analytics
                                ga('send', 'event', 'masterklass7', 'register');
                                yaCounter27714603.reachGoal('lm17lead');
                            });
                        break;
                    // Если у формы id="popupResult" - делаем:
                    case 'popupResult':
                        $.ajax({
                                type: 'POST',
                                url: $form.attr('action'),
                                data: $form.serialize(),
                            })
                            .always(function(response) {
                                setTimeout(function() {
                                    $('#loader').fadeOut();
                                }, 800);
                                setTimeout(function() {
                                    $('#overlay').fadeIn();
                                    $form.trigger('reset');
                                    $('input, textarea').removeClass('error, valid');
                                    //строки для остлеживания целей в Я.Метрике и Google Analytics
                                }, 1100);
                                $('#overlay').on('click', function(e) {
                                    $(this).fadeOut();
                                });
                            });
                            if($('*').is('#myModal')) {
                                $('#myModal').arcticmodal('close');
                            };
                        break;
                }
                return false;
            }
        })
    }

    // Запускаем механизм валидации форм, если у них есть класс .js-form
    $('.js-form').each(function() {
        valEl($(this));
    });
     
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Boychenko, 2020-04-17
@struggler

1. It is very strange to pull a whole lib into the project to do form validation when there is native validation with which you can do the same in a couple of lines of code.
2. You need to hang up a handler to change the text field.

$(':input').on('input keyup change paste', function(){
  if($(this).hasClass('error')) {
    $(this).removeClass('error');
  }
});
$(':input').on('blur', function(){
  if($(this).val() == '') {
    $(this).removeClass('error');
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question