dmitriy
dmitriy

Reputation: 488

Issue with validation of a form on submit?

I have a problem with my code. It is not working correctly. When you start filling the form you fill your name, then you fill phone. If you click with mouse the form is not submitted until you click somewhere else before clicking the submit button or click twice on submit button or press ENTER. Why this happens?

I want that after fill in the last field I can click mouse on submit and it will work.

//validation name
    document.myform.name.onchange= function() {
        var name = document.myform.name.value;
        if (name === "") {
            document.myform.name.removeAttribute("class", "ready");
            document.myform.name.style.border = "1px solid #da3637";
            document.getElementById("Error").style.display = "block";
            document.getElementById("ErrorTwo").style.display = "none";
        } else {
                document.myform.name.style.border = "1px solid #509d12";
                document.getElementById("Error").style.display = "none";
                var pattern = new RegExp("^[а-я]+$", "i");
                var isValid = this.value.search(pattern) >= 0;
                if (!(isValid)) {
                    document.myform.name.style.border = "1px solid #da3637";
                    document.getElementById("ErrorTwo").style.display = "block";
                    document.myform.name.removeAttribute("class", "ready");
                } else {
                    document.getElementById("ErrorTwo").style.display = "none";
                    document.myform.name.style.border = "1px solid #509d12";
                    document.myform.name.setAttribute("class", "ready");
                }
        }
    };


    //validation phone
    document.myform.phone.onchange = function() {
        var name = document.myform.phone.value;
        if (name === "") {
            document.myform.phone.removeAttribute("class", "ready");
            document.myform.phone.style.border = "1px solid #da3637";
            document.getElementById("telError").style.display = "block";
            document.getElementById("telErrorTwo").style.display = "none";
        } else {
                document.myform.phone.style.border = "1px solid #509d12";
                document.getElementById("telError").style.display = "none";
                var pattern = new RegExp("[- +()0-9]+");
                var isValid = this.value.search(pattern) >= 0;

                if (!(isValid)) {
                    document.myform.phone.style.border = "1px solid #da3637";
                    document.getElementById("telErrorTwo").style.display = "block";
                } else {
                    document.getElementById("telErrorTwo").style.display = "none";
                    document.myform.phone.style.border = "1px solid #509d12";
                    document.myform.phone.setAttribute("class", "ready");
                }
            }
    };

    //filling the form
    document.myform.onchange = function() {
        var a = document.myform.name.getAttribute("class");
        var c = document.myform.phone.getAttribute("class");
        if (a === "ready" && c === "ready") {
            document.getElementById("save").removeAttribute("disabled");
            document.getElementById("save").style.cursor = "pointer";
            document.getElementById("save").style.opacity = "1";
        }
    };

    $(".callback-submit").click(function() {

    var url = "send.php"; 

    $.ajax({
           type: "POST",
           url: url,
           data: $("#callForm form").serialize(), 
           success: function(data)
           {
               var name = $("input[name=name]").val("");
               var rel= $("input[name=phone]").val("");
               $("#flipTwo").addClass("animateTwo");
           }
         });

    return false; // avoid to execute the actual submit of the form.
    });

html:

<div class="callback-form" id="callForm">
            <form name='myform'>
                <span class="close-btn" id="close">&#10006;</span>
                <p>Введите свои контактные данные</p>
                <p>Мы Вам перезвоним</p>
                <input type="text" name="name" placeholder="Имя" maxlength="30">
                <p class="Error" id="Error">Это поле обязательное для заполнения</p>
                <p class="ErrorTwo" id="ErrorTwo">Некорректный ввод</p>
                <input type="tel" name="phone" placeholder="Телефон" maxlength="20" minlength="7">
                <p class="Error" id="telError">Это поле обязательное для заполнения</p>
                <p class="ErrorTwo" id="telErrorTwo">Некорректный ввод</p>
                <div id="flipTwo">
                    <input class="callback-submit" type="submit" value="Отправить заявку"  name="save" id="save" disabled>
                    <span id="iconCheckTwo">Отправлено<i class="fa fa-check" aria-hidden="true"></i></span>
                </div>
                <p>Данные не передаються третьим лицам</p>
            </form>
        </div>

Upvotes: 1

Views: 77

Answers (1)

Ruhul Amin
Ruhul Amin

Reputation: 1779

I think you can make it in more organised way, First make little clean up on your html code

like: `

Введите свои контактные данные

Мы Вам перезвоним

Это поле обязательное для заполнения

Некорректный ввод

Это поле обязательное для заполнения

Некорректный ввод

    <div class="group">
        <div id="flipTwo">
            <input class="callback-submit" type="submit" value="Отправить subtmi"  name="save" id="save">
            <span id="iconCheckTwo">Отправлено<i class="fa fa-check" aria-hidden="true"></i></span>
        </div>
    </div>

    <p>Данные не передаються третьим лицам</p>
</form>`

And then write clean code for your jQuery and structured. I did partial and I hope you can complete your rest:

 jQuery(document).ready(function($) {

    $('#myform').on('submit', function(){
        var form = this;
        if(validateForm(form)) {
            var values = $(form).serialize();
            var url = "send.php";
            $.ajax({
                url: url,
                type: "post",
                data: values ,
                success: function (data) {
                    var name = $("input[name=name]").val("");
                    var rel= $("input[name=phone]").val("");
                    $("#flipTwo").addClass("animateTwo");
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(textStatus, errorThrown);
                }


            });
            event.preventDefault(); //changed to allow the tag manager to notice that the form was submitted
        }
        else{
            event.preventDefault();
            return false;
        }
    });

    // validate Form
    function validateForm(form) {
        valid = true;

        $(form).find('input[type=text], input[type=email]').each(function(i, val){
            if(validateField(val, true) == false) { valid = false; }
        });

        return valid;
    }

    // validate all form fields
    function validateField(field, submit) {
        var val = $(field).val();
        if(submit){

            // you can more specific
            if($(field).attr('name') == 'name' && val == '') {
                $(field).parent().find('#Error').show();
                $(field).parent().find('#ErrorTwo').hide();
                return false; }
            else if (!isValidName(val)){
                // your next rule
                return false;
            }
            // same way for email
            if($(field).attr('type') == 'email') {
                $(field).parent().addClass('error');
                return false; }
            else if (!isValidName(val)){
                // your next rule
                return false;
            }
        }
    }
    function isValidName(name) {
        var pattern = new RegExp(/^[а-я]+$/);
        return pattern.test(no);
    }
    function isValidPhone(no) {
        var pattern = new RegExp(/[- +()0-9]+/);
        return pattern.test(no);
    }
    // Run validation before Submit the form
    $('input[type=text], input[type=email]').on('change', function(){
        if($(this).val() != ''){
            $(this).parent().removeClass('error valid');
            validateField(this, false);
        }
    });
});

JSfiddle: https://jsfiddle.net/n32c2dwo/4/

Upvotes: 1

Related Questions