Rick Bross
Rick Bross

Reputation: 1082

Why isnt my form validating

So, all of a sudden, my form stopped validating, its viewable live from: http://scoutsamerica.com/beamodel.php

I haven't edited it at all, and it was working fine the other day.. It's allowing the user to pass through without uploading an image.

Here is the Javascript on the page:

 <script type="text/javascript">

    function Validate(oForm) {
        if(!countWords("full_name", 2, "Please input your first and last name.")) {
            return false; // Name didnt validate.
        }
        if(!checkemail("email")) {
            return false; // Email didnt validate.
        }
        if(!checkAge("age")) {
            return false; // Age didnt validate.
        }
        if(!checkTwitter("twitter")) {
            return false; // Twitter didnt validate.
        }
        if(!checkZip("zip")) {
            return false; // Twitter didnt validate.
        }
        if(!checkPhone("phone")) {
            return false; // Twitter didnt validate.
        }
        if(!checkFileFormat(oForm)) {
            return false; // File didnt validate.
        }
        checkFileSize("uploadedfile");
    };

    $(document).ready(function(){

        $("#twitter").blur(function() {
            var s = $("#twitter").val();
            var isAt = s.charAt(0);
            if(isAt !== "@") {
                $(this).val('@' + s);
            }
        });

        function checkCity(s){
            return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
        };

        $("#city").blur(function() {
            var s = $("#city").val();
            var isAt = s.charAt(0);
            if(isAt !== "@") {
                $(this).val(checkCity(s));
            }
        });
        $("#phone").blur(function() {
            var phone = $(this).val();

            phone = phone.replace(/\D/g, '');
            if (phone.length == 10) {
                var areaCode = phone.substring(0,3);
                var phoneFirst = phone.substring(3,6);
                var phoneLast = phone.substring(6,10);

                var formattedNumber = areaCode + '-' + phoneFirst + '-' + phoneLast;
                $(this).val(formattedNumber);
            }

        });
        $("#age").blur(function() {
            var age = $(this).val();
            if (age < 18) {
                $(".contactHalf").addClass("young");
                $(".parent").show();
            } else {
                $(".contactHalf").removeClass("young");
                $(".parent").hide();
            }

        });
        //binds to onchange event of your input field
        $('#uploadedfile').bind('change', function() {
            var sizeInBytes = this.files[0].size;


            console.log("Bytes: " + sizeInBytes); //6561060
            console.log("Megabytes: " + (sizeInBytes / (1024*1024)).toFixed(2) + " mb"); //6561060

        });
    });

 </script>

Here is my validate.js page and how it is being referenced on my page:

<script type='text/javascript' src='../js/validate.js'></script>

validate.js:

    function checkemail(email){
        var str=document.getElementById(email).value;
        var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

        if (filter.test(str)) {
            testresults=true
        } else {
            alert("Please input a valid email address!")
            testresults=false
        }
        return (testresults)
    }
    $("#beamodelform").submit(function(){
        var isFormValid = true;

        $("#beamodelform input").each(function(){
            if ($.trim($(this).val()).length == 0){
                $(this).addClass("highlight");
                isFormValid = false;
            }
            else{
                $(this).removeClass("highlight");
            }
        });

        if (!isFormValid) alert("Please fill in every field.");

        return isFormValid;
    });
    function countWords(theField, theMax, msg){
        s = document.getElementById(theField).value;
        s = s.replace(/(^\s*)|(\s*$)/gi,"");
        s =s.replace(/[ ]{2,}/gi," ");
        s = s.replace(/\n /,"\n");
        var strLen = s.split(' ').length;

        if (strLen > theMax) {
            alert(msg);
            return false;
        } else {
            return true;
        }
    }
    function checkAge(ageID) {
        var age = document.getElementById(ageID).value;
        if(isNaN(age)) {
            alert("Please input a valid age.");
            return false;
        } else {
            return true;
        }
    }
    function checkTwitter(twitterName) {
        var twitterName = document.getElementById(twitterName).value;
        var isIt = (twitterName.indexOf(" ") !== -1);
        if(isIt) {
            alert("Please input a Twitter username.");
            return false;
        } else {
            return true;
        }
    }
    function checkZip(zipId) {
        var zip = document.getElementById(zipId).value;
        zip = zip.replace(/ /g,'');
        if(isNaN(zip)) {
            alert("Please input a valid ZIP code.");
            return false;
        } else {
            if (zip.length !== 5) {
                alert("Please input a valid ZIP code.");
                return false;
            } else {
                return true;
            };
        }
    }
    function checkPhone(phoneNum) {
        var phoneEnt = document.getElementById(phoneNum).value;
        var phoneNum = phoneEnt.replace(/\D/g, '');
        if(phoneNum.length !== 10) {
            alert("Please input a valid phone number.");
            return false;
        } else {
            return true;
        }
    }
    function checkFileFormat(oForm) {

        var _validFileExtensions = [".jpg", ".jpeg", ".JPG", ".JPEG"];
        // For Files
        var arrInputs = oForm.getElementsByTagName("input");
        for (var i = 0; i < arrInputs.length; i++) {
            var oInput = arrInputs[i];
            if (oInput.type == "file") {
                var sFileName = oInput.value;
                if (sFileName.length > 0) {
                    var blnValid = false;
                    for (var j = 0; j < _validFileExtensions.length; j++) {
                        var sCurExtension = _validFileExtensions[j];
                        if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                            blnValid = true;
                            break;
                        }
                    }
                    if (!blnValid) {
                        alert("Sorry, your image is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                        return false;
                    }
                } else {
                    alert("Please upload an image.");
                    return false;
                }
            }
        }
        return true;
    };

    function checkFileFormat(uploader) {
        var uploaded = document.getElementById(uploader).value;
        var pic = uploaded.files[0];
        //this.files[0].size gets the size of your file.
        alert(pic.size);

    };

Here is my form:

<div id="contactScoutsAmerica" class="mainContent">
            <h1>Be A Model</h1>
            <p>Request to be a <img height="19" src="/img/navSA.png" /> Model today!</p>

        <form method="post" id="beamodelform" name="beamodel" action="modelrequest.php" enctype="multipart/form-data" onsubmit="return Validate(this)">
            <div class="contactHalf" id="leftHalf">
                    <div class="contactbrake">
                        <input tabindex="1" type="text" id="full_name" name="full_name" placeholder="Jane Doe" required></input>
                        <input tabindex="2" type="text" id="email" name="email" placeholder="i.e. [email protected]" required></input>
                        <label>Name</label>
                        <label>Email</label>
                    </div>
                    <div class="contactbrake">
                        <input tabindex="5" type="text" id="address" name="address" placeholder="4300 Main St." required></input>
                        <input tabindex="6" type="text" id="city" name="city" placeholder="Kansas City" required></input><br>
                        <label>Address</label>
                        <label>City</label>
                    </div>

                    <div class="contactbrake" id="lastleft">
                        <input tabindex="10" type="text" id="timeofday" name="timeofday" placeholder="After 5:30PM" required></input>
                        <input tabindex="11" type="text" id="dayofweek" name="dayofweek" placeholder="Weekdays"></input><br>
                        <label id="timeofdaylabel">Best Time to Call</label>
                        <label id="dayofweeklabel">Day of Week</label>
                    </div>
                    <div class='contactbrake parent'>
                        <input tabindex='12' type='text' id='parentname' name='parentname' placeholder='John Doe'></input>
                        <input tabindex='13' type='text' id='parentnumber' name='parentnumber' placeholder='816-555-2401'></input><br>
                        <label id='timeofdaylabel'>Parent Name</label>
                        <label id='dayofweeklabel'>Parent Phone Number</label></div>
                    <div class="contactbrake">
                        <p>If you are reading this there is a very good chance you have heard about us on the radio, been spotted by one of our talent scouts, or referred by one of our models. If so, congratulations! You have taken the first step to becoming a model or actor with Scouts America. Just fill out this simple application and a representative will contact you within 48 hours.</p>
                    </div>
            </div>
            <div class="contactHalf" id="rightHalf">
                    <div class="contactbrake">
                        <input tabindex="3" type="text" id="age" name="age" placeholder="18" required></input>
                        <input tabindex="4" type="text" id="twitter" name="twitter" placeholder="@ScoutsAmerica"></input>
                        <label>Age</label>
                        <label>Twitter</label>
                    </div>

                    <div class="contactbrake">
                        <select tabindex='7' name="state" id="state" style="width: 49px !important;">
                            <option value="AL">AL</option>
                            <option value="AK">AK</option>
                            <option value="AZ">AZ</option>
                            <option value="AR">AR</option>
                            <option value="CA">CA</option>
                            <option value="CO">CO</option>
                            <option value="CT">CT</option>
                            <option value="DE">DE</option>
                            <option value="DC">DC</option>
                            <option value="FL">FL</option>
                            <option value="GA">GA</option>
                            <option value="HI">HI</option>
                            <option value="ID">ID</option>
                            <option value="IL">IL</option>
                            <option value="IN">IN</option>
                            <option value="IA">IA</option>
                            <option value="KS">KS</option>
                            <option value="KY">KY</option>
                            <option value="LA">LA</option>
                            <option value="ME">ME</option>
                            <option value="MD">MD</option>
                            <option value="MA">MA</option>
                            <option value="MI">MI</option>
                            <option value="MN">MN</option>
                            <option value="MS">MS</option>
                            <option value="MO">MO</option>
                            <option value="MT">MT</option>
                            <option value="NE">NE</option>
                            <option value="NV">NV</option>
                            <option value="NH">NH</option>
                            <option value="NJ">NJ</option>
                            <option value="NM">NM</option>
                            <option value="NY">NY</option>
                            <option value="NC">NC</option>
                            <option value="ND">ND</option>
                            <option value="OH">OH</option>
                            <option value="OK">OK</option>
                            <option value="OR">OR</option>
                            <option value="PA">PA</option>
                            <option value="RI">RI</option>
                            <option value="SC">SC</option>
                            <option value="SD">SD</option>
                            <option value="TN">TN</option>
                            <option value="TX">TX</option>
                            <option value="UT">UT</option>
                            <option value="VT">VT</option>
                            <option value="VA">VA</option>
                            <option value="WA">WA</option>
                            <option value="WV">WV</option>
                            <option value="WI">WI</option>
                            <option value="WY">WY</option>
                        </select>
                        <input tabindex="8" type="text" id="zip" name="zip" placeholder="64130" required></input>
                        <input tabindex="9" type="text" id="phone" name="phone" placeholder="816-555-2400" required></input><br>
                        <label id="statelabel">State</label>
                        <label id="ziplabel">ZIP</label>
                        <label id="phonelabel">Phone</label>
                    </div>

                    <div class="contactbrake" id="lastright">
                        <input type="hidden" name="MAX_FILE_SIZE" value="7500000" />
                        <input type="file" name="uploadedfile" id="uploadedfile" text="Attach File" />
                        <label id="attachfile">Attach image of yourself</label>
                    </div>
                    <div class='contactbrake parent'>
                    </div>
                    <div class="contactbrake">
                        <textarea id="contactMsg" name="contactMsg" autocomplete="off" placeholder="Send us a message!"></textarea>
                        <button type="submit">Send</button>
                    </div>
                </div>
            </form>
        </div>

Upvotes: 0

Views: 191

Answers (2)

Mathijs Flietstra
Mathijs Flietstra

Reputation: 12974

You have a checkFileFormat(uploader) and a checkFileFormat(oForm) function? I don't think JS will know which one to call.

Are you using a different browser than the other day? I just filled out the form on the live page, and it works fine. It is not letting me pass without uploading an image. I'm using Chrome here.

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71384

You have two functions defined as checkFileFormat() there is nothing defined for checkFileSize(). I am guessing the second should actually be named checkFileSize().

function checkFileFormat(uploader) {  // <-- Change name here?
    var uploaded = document.getElementById(uploader).value;
    var pic = uploaded.files[0];
    //this.files[0].size gets the size of your file.
    alert(pic.size);

};

Second, in the Validate() function, it seems you would need to return false if file size is 0, here you just call the method and don't conditionally return a false.

checkFileSize("uploadedfile");

Upvotes: 1

Related Questions