billy98111
billy98111

Reputation: 99

Javascript/jQuery form validation

I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out a way to make the error text disappear with the way that I am doing this. Also I know I have the option of PHP validation but there is a few reasons why I want to use this front end validation. Here is the whole validation script for the form. The submit portion is at the bottom:

JavaScript/jQuery

    var valid = 0;

    function checkName(elem) {

        //gather the calling elements value
        var val = document.getElementById(elem.id).value;
        //Check length
        if (val.length<1) {
            document.getElementById("errorName").innerHTML = "<span>Don't forget your name.</span>";

        } else if (val.length>40){
            document.getElementById("errorName").innerHTML = "<span>This doesn't look like a name.</span>";
        //If valid input increment var valid.
        } else {
            document.getElementById("errorName").innerHTML = "";
            valid++;

        }
    }

    function checkEmail(elem) {

        var val = document.getElementById(elem.id).value;
        //Check email format validity
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (!re.test(val)) {
            document.getElementById("errorEmail").innerHTML = "<span>Please enter a valid email.</span>";
        } else {
            document.getElementById("errorEmail").innerHTML = "";
            valid++;
        }
    }

    function checkMessage(elem) {

        var val = document.getElementById(elem.id).value;

        if (val.length<1) {
            document.getElementById("errorMessage").innerHTML = "<span>It looks like you forgot the message.</span>";

        } else if (val.length>2000) {
            document.getElementById("errorMessage").innerHTML = "<span>It looks like your message is too long.</span>";

        } else {
            document.getElementById("errorMessage").innerHTML = "";
            valid++;    
        }

    }


//Contact: jQuery check for null/empty/errors
$(document).ready(function() {

function checkSubmit() {
    if (valid == 3) {
        document.getElementById("errorSubmit").innerHTML = "";
    }
}

//If errors when submitting display message

$('#form13').submit(function(submit) {
    if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
        document.getElementById("errorSubmit").innerHTML = "<span>Please fill out all the form fields.</span>";
        submit.preventDefault();
    } else if (valid < 3) {
        document.getElementById("errorSubmit").innerHTML = "<span>Please check the errors above.</span>";
        submit.preventDefault();
    }
  })
});

HTML Form

 <div class="row"> 
            <div class="col-md-8 col-md-offset-2"> 
                <div class="cform" id="contact-form"> 
                    <form id="form13" name="form13" role="form" class="contactForm" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate
  action="https://Some3rdPartyPOSTService"> 
                        <div class="form-group"> 
                            <label for="name">Your Name</label>                                 
                            <input type="text" name="Field1" class="form-control" id="name" placeholder="Tony Stark" onblur="checkName(this)"/>
                            <span id="errorName" style="margin-left:10px;"></span>                                                              
                        </div>                             
                        <div class="form-group"> 
                            <label for="email">Your Email</label>                                 
                            <input type="email" class="form-control" name="Field4" id="email" placeholder="" data-rule="email" data-msg="Please enter a valid email" onblur="checkEmail(this)"/>
                            <span id="errorEmail" style="margin-left:10px;"></span>                                  
                        </div>                                                     
                        <div class="form-group"> 
                            <label for="message">Message</label>                                 
                            <textarea class="form-control" name="Field3" id="message" rows="5" data-rule="required" data-msg="Please write something here" onblur="checkMessage(this)"></textarea>  
                            <span id="errorMessage" style="margin-left:10px;"></span>                                
                        </div>
                        <span id="errorSubmit" style="margin-left:10px;"></span>
                        <button type="submit" class="btn btn-theme pull-left">SEND MESSAGE</button>
                    </form>                         
                </div>                     
            </div>                 
            <!-- ./span12 -->                 
        </div>             
    </div>         
</section>     

Upvotes: 0

Views: 488

Answers (3)

Magicprog.fr
Magicprog.fr

Reputation: 4100

I've removed your onblur html attributes and replaced them by JavaScript keyup events. This will allow your script to check everything as soon as the user type something :

document.getElementById("message").addEventListener('keyup', function () {
    checkMessage(this);
});
document.getElementById("email").addEventListener('keyup', function () {
    checkEmail(this);
});
document.getElementById("name").addEventListener('keyup', function () {
    checkName(this);
});

JSFIDDLE

Upvotes: 1

Schleis
Schleis

Reputation: 43690

Add an onchange event to your text inputs that will remove the error message.

Rather than making a count of valid fields, I would also check for the existence of error messages. This will make it easier to add more fields to your form.

function checkName(e) {
        //gather the calling elements value
        var val = $(e.target).val();
        //Check length
        if (val.length<1) {
            document.getElementById("errorName").innerHTML = "<span class="errmsg">Don't forget your name.</span>";

        } else if (val.length>40){
            document.getElementById("errorName").innerHTML = "<span class='errmsg'>This doesn't look like a name.</span>";
        //If valid input increment var valid.
        } else {
            document.getElementById("errorName").innerHTML = "";

        }
    }

    function checkEmail(e) {

        var val = $(e.target).val();
        //Check email format validity
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (!re.test(val)) {
            document.getElementById("errorEmail").innerHTML = "<span class='errmsg'>Please enter a valid email.</span>";
        } else {
            document.getElementById("errorEmail").innerHTML = "";
        }
    }

    function checkMessage(e) {

        var val = $(e.target).val();

        if (val.length<1) {
            document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like you forgot the message.</span>";

        } else if (val.length>2000) {
            document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like your message is too long.</span>";

        } else {
            document.getElementById("errorMessage").innerHTML = ""; 
        }

    }


//Contact: jQuery check for null/empty/errors
$(document).ready(function() {

    $('#name').change(checkName);
    $('#email').change(checkEmail);
    $('#message').change(checkMessage);

    function checkSubmit() {
        if ($('form .errmsg').length > 0) {
            document.getElementById("errorSubmit").innerHTML = "";
        }
    }
}

/If errors when submitting display message

$('#form13').submit(function(submit) {
    if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
        document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please fill out all the form fields.</span>";
        submit.preventDefault();
    } else if ($('form .errmsg').length > 0) {
        document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please check the errors above.</span>";
        submit.preventDefault();
    }
  })
});

Since you were already using jQuery, I modified the code to use more of the jQuery functionality to make things easier. Now when a form field is modified and the element loses focus, the validation will occur immediately. We also no longer need to know how many error messages could potentially appear (though you never had a decrement operation for corrected values so the valid could become greater than 3). Instead we just make sure that there isn't more than 0 of them.

Upvotes: 1

Marijan Spasenovski
Marijan Spasenovski

Reputation: 104

Simply put your check on onChange event callback, if:

var x = getElementById("formid"); //  then add a listener     
x.addEventListener('change', function () {

   callback with your code that examines the form

});

Or listen for a specific text box change event, that would be the simplest way, and look for a way to disable submit if the conditions aren't met.

Upvotes: 3

Related Questions