简体   繁体   中英

Simple form validation isn't working properly

So I'm trying to implement a simple form validation script to run on my web server and I cant manage to figure out why it won't work.

From running some tests of the code it seems that the comments section validation is done fine but the email and subject sections aren't validated properly and continue to display the error messages even when the input values should technically satisfy the conditions.

Javascript:

function validateForm(){
var validEmail, validSubject, validComment = true;
var validDocument = true;

var emailEntry =document.forms["contact_form"]["email"].value;
var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!pattern.test(emailEntry)) {
    //Not a valid email
    validEmail = false;
}
var subjectEntry = document.forms["contact_form"]["subject"].value;
if(subjectEntry.length < 6) {
    //Not a valid subject
    validSubject = false;
}
var commentsEntry = document.forms["contact_form"]["comments"].value;
if(commentsEntry.length < 50) {
    //Not a valid comment
    validComment = false;
}

var err1 = document.getElementById("email_error");
var err2 = document.getElementById("subject_error");
var err3 = document.getElementById("comment_error");

if(!validEmail) {
    //make error messages visible
    validDocument = false;
    err1.style.visibility = "visible";
} else {
    err1.style.visibility = "hidden";
}

if(!validSubject) {
    //make error messages visible
    validDocument = false;
    err2.style.visibility = "visible";
} else {
    err2.style.visibility = "hidden";   
}

if(!validComment) {
    //make error messages visible
    validDocument = false;
    err3.style.visibility = "visible";
} else {
    err3.style.visibility = "hidden";   
}

if(!validDocument) {
    var container = document.getElementById("errors");
    container.style.visibility = "visible";
    return false;   
} else {
    return true;
}}

HTML:

<div id="contact_fields">
            <form name="contact_form" onSubmit="return validateForm()" method="post" action="form_mailer.php">

                <font class="form_headers" face="Arial, Helvetica, sans-serif" size="4" color="#FFF">
                Your e-mail address :
                </font>

                <br><input type="text" name="email" id="email" value="" size="40" 
                style="height:10%;font-size:1.3vw;">
                <br><br><br><br>


                <font class="form_headers" face="Arial, Helvetica, sans-serif" size="4" color="#FFF">
                Subject :
                </font>

                <br><input type="text" name="subject" id="subject" value="" size="40"
                style="height:10%;font-size:1.3vw;">
                <br><br><br><br>


                <font class="form_headers" face="Arial, Helvetica, sans-serif" size="4" color="#FFF">
                Message :
                </font>

                <br><textarea name="comments" id="comments" rows="8" cols="40"
                style="font-size:1.3vw;"></textarea>
                <br>
                <font face="Arial, Helvetica, sans-serif" size="2" color="#FFF">
                 &bull; You must fill in all fields in order to submit.
                </font>
                <br>
                <input type="submit" name="Submit" value="submit" style="float:right;">
            </form>


        </div>



        <div id="errors" style="visibility:hidden">
            <p><font id="email_error" face="Arial, Helvetica, sans-serif" style="visibility:hidden" color="#FF0000">
                *Enter a valid e-mail</font></p>
            <p><font id="subject_error" face="Arial, Helvetica, sans-serif" style="visibility:hidden" color="#FF0000">*Subject must be at least 6 characters</font></p>
            <p><font id="comment_error" face="Arial, Helvetica, sans-serif" style="visibility:hidden" color="#FF0000">*Message must be at least 50 characters</font></p>
        </div>

EDIT 1: Forgive the really nasty break tags in the html, it's a bit rushed.

EDIT 2: Changed email validation to RegEx but to no avail.

Tips

  • separation of duties will make debugging easier. Each function should do one thing and do it well.
  • use arrays for data of similar structure
  • use loops if you see a pattern in your code

The Validator

  • For your use case, you want to validate a variety of fields, but you find coding each one tedious. Solution, make a general validator

Below is the code for a generic validator

function validator(/*fn, args */) {
    var predicate = arguments[0];
    var args = Array.prototype.splice.call(arguments, 1);

    return function() {
        return (predicate.apply(null, arguments) == true);
    };
};

This function will allow you to create more specific validators that you can reuse later on. It's not complete validator by any means, but it's a start.

Specific Validators

Once you have a general validator, you can start coding your specific validators. In this case, we have two validators. Is a value an email and is a string greater than some length. Don't worry about the e-mail one, I just ripped it from the regex library . You can use one that fits your needs.

var isEmail = validator(function(email) {
    return /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email);
});

var isStringLengthGreaterThan = validator(function(value, length) {
    return (value.length > length);
});

Validating a field

Let's create a generalized form validator. So we'll start with validating a single field. Here we go. This code will take in the arguments and assume that the first three are the formId, fieldId, and a validator. All extra arguments are considered arguments for the validator.

function isFieldValid(formId, domId, validatorFn) {
    var args = Array.prototype.splice.call(arguments, 3);
    args.unshift( document.forms[formId][domId].value );
    return validatorFn.apply(null, args);
};

Putting it all together

I got lazy here (it's lunch time), but you can now put everything in collections and loop through them. You could create a function called doWhen and use the syntax doWhen(!isFieldValid(...), printErrorMessage(...)) , but I'll leave that to you to figure it out.

function validateForm(){
    var validFields = [    
        isFieldValid('contact_form', 'email', isEmail),
        isFieldValid('contact_form', 'subject', isStringLengthGreaterThan, 6),
        isFieldValid('contact_form', 'comments', isStringLengthGreaterThan, 50)
    ];

    var errorDomId = ["email_error", "subject_error", "comment_error"];

    validFields.forEach(function(isValid, index) {
        if ( isValid == false) {
            document
                .getElementById(errorDomId[index])
                .style
                .visibility = 'visible';
        };
    });

    if (validFields.indexOf(false) > -1) {
        var container = document.getElementById("errors");
        container.style.visibility = "visible";
    }

    return  (validFields.indexOf(false) == -1);
}

Summary

The key is to put your data in collections, keep your functions simple, and loop through the collections of data to execute actions and/or functions against them. It should be noted that the forEach method doesn't work in IE < 9. You can replace that with a regular for loop if you want. However, I use it for readability reasons. Good luck and happy coding!

jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM