PHP + Javascript Validation

have created a form that sends the contents to a mysql database.
i want the form to be validated using javascript b4 hand, it works without the php to get it to send to the database but when i press submit, it won’t validate here is my code…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Untitled Document</title>

</head>



<body>

<script language="JavaScript">

<!-



function formCheck(formobj){

    // Enter name of mandatory fields

    var fieldRequired = Array("FirstName", "LastName", "EmailAddress","Question1", "Question2", "Question3", "Question4", "Question5");

    // Enter field description to appear in the dialog box

    var fieldDescription = Array("First Name", "Last Name", "EmailAddress", "Question1", "Question2","Question3", "Question4", "Question5");

    // dialog message

    var alertMsg = "Please complete the following fields:\
";

    

    var l_Msg = alertMsg.length;

    

    for (var i = 0; i < fieldRequired.length; i++){

        var obj = formobj.elements[fieldRequired[i]];

        if (obj){

            switch(obj.type){

            case "text":

            case "textarea":

                if (obj.value == "" || obj.value == null){

                    alertMsg += " - " + fieldDescription[i] + "\
";

                }

                break;

            default:

            }

            if (obj.type == undefined){

                var blnchecked = false;

                for (var j = 0; j < obj.length; j++){

                    if (obj[j].checked){

                        blnchecked = true;

                    }

                }

                if (!blnchecked){

                    alertMsg += " - " + fieldDescription[i] + "\
";

                }

            }

        }

    }



    if (alertMsg.length == l_Msg){

        return true;

    }else{

        alert(alertMsg);

        return false;

    }

}

// -->

</script>



<form method="POST" action="<? echo ( $self ); ?>"

<form name="formcheck" onsubmit="return formCheck(this);">

<form action="insert_record.php" method="POST">



First Name: <input type=text name="FirstName" size="25"><br>

Last Name: <input type=text name="LastName" size="25"><br>

E-mail Address: <input type=text name="EmailAddress" size"25" /><br />

Question1: <input type=text name="Question1" size"25" /><br />

Question2: <input type=text name="Question2" size"25" /><br />

Question3: <input type=text name="Question3" size"25" /><br />

Question4: <input type=text name="Question4" size"25" /><br />

Question5: <input type=text name="Question5" size"25" /><br />

Question6: <input type=text name="Question6" size"25" /><br />

Question5: <input type=text name="Additions" size"25" /><br />





<input type=submit value="Submit Form">

</form>



<?php



include("dbinfo.inc.php");

$comm=@mysql_connect(localhost,$username,$password);

$rs=@mysql_select_db($database ) or die( "Unable to select database");



$self = $_SERVER['PHP_SELF'];



@$FirstName=$_POST['FirstName'];

@$LastName=$_POST['LastName'];

@$Question1=$_POST['Question1'];

@$Question2=$_POST['Question2'];

@$Question3=$_POST['Question3'];

@$Question4=$_POST['Question4'];

@$Question5=$_POST['Question5'];

@$Question6=$_POST['Question6'];

@$Additions=$_POST['Additions'];



if($FirstName){



$sql="INSERT INTO contact ( FirstName, LastName, EmailAddress, Question1, Question2, Question3, Question4, Quesion5, Question6, Additions) VALUES ( '$FirstName','$LastName','$EmailAddress','$Question1','$Question2','$Question3','$Question4','$Question5','$Question6','$Additions')";



$result=mysql_query($sql)or die("Insert Error: ".mysql_error());



if($result){

print "Record added\
";

}



}

?>

</body>

</html>

At a quick glace you have 3 form elements which is why your validation is not working, it should only need to be the below as one element.

<form action="insert_record.php" method="post" onsubmit="return formCheck(this);" name="formcheck">

Also your script is malformed which means it contains security issues.

cheers mate i owe you one, its only a test for a project im doing. but it seems to be working now. Taken me all weekend to work that out. Really should learn javascript properly i think. Cheers for your help, your a better man than i am! :rofl:

I thought because your learning this may help you, i have overhauled your code which is now secure and contains some updated code. Let me me know how it goes for you.

<?php

if (isset($_POST['submit'])) {
    include('dbinfo.inc.php');
    
    // Create a new database connection
    $con = mysql_connect('localhost', $username, $password);
    mysql_select_db($database, $con) or die('Unable to select database');
    
    // Validate the fields, always use backend validation to
    // ensure all values are correct and never just hope the
    // front end validation is correct
    $requiredFields = array(
        array('name' => 'FirstName', 'desc' => 'First Name'),
        array('name' => 'LastName', 'desc' => 'Last Name'),
        array('name' => 'EmailAddress', 'desc' => 'Email Address'),
        array('name' => 'Question1', 'desc' => 'Question 1'),
        array('name' => 'Question2', 'desc' => 'Question 2'),
        array('name' => 'Question3', 'desc' => 'Question 3'),
        array('name' => 'Question4', 'desc' => 'Question 4'),
        array('name' => 'Question5', 'desc' => 'Question 5'),
        array('name' => 'Question6', 'desc' => 'Question 6')
    );
    
    $insertMsg = 'Please complete the following fields:<br /><br />';
    $errors = 0;
    
    foreach($requiredFields as $required) {
        if (isset($_POST[$required['name']])) {
            // Escape any unwanted data and strip all HTML tags
            // from the field value
            $_POST[$required['name']] = mysql_real_escape_string($_POST[$required['name']]);
            $_POST[$required['name']] = strip_tags($_POST[$required['name']]);
            
            if (strlen($_POST[$required['name']]) == 0 || empty($_POST[$required['name']])) {
                $insertMsg .= '- ' . $required['desc'] . '<br />';
                $errors++;
            }
        }
    }
    
    // If no form errors exist run the MySQL query
    if (!$errors) {
        $firstname = $_POST['FirstName'];
        $lastname = $_POST['LastName'];
        $emailaddress = $_POST['EmailAddress'];
        $question1 = $_POST['Question1'];
        $question2 = $_POST['Question2'];
        $question3 = $_POST['Question3'];
        $question4 = $_POST['Question4'];
        $question5 = $_POST['Question5'];
        $question6 = $_POST['Question6'];
        $additions = $_POST['Additions'];
        
        $sql = "INSERT INTO contact (FirstName, LastName, EmailAddress, Question1, Question2, Question3, Question4, Quesion5, Question6, Additions) VALUES ('$firstname', '$lastname', '$emailaddress', '$question1', '$question2', '$question3', '$question4', '$question5', '$question6', '$additions')";
        
        $insertMsg = mysql_query($sql) ? '<font color="green">Record added successfully!</font><br />' : '<font color="red">Failed to add record:</font><br />' . mysql_error() .'<br />';
    }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form Validation Testing</title>
<script language="JavaScript">
//<![CDATA[
function inArray(array, value) {
    for(var i in array) {
        if (array[i] == value) {
            return true;
            break;
        }
    }
    
    return false;
}

function formCheck(form) {
    // Required fields
    var requiredFields = [
        {name: 'FirstName', desc: 'First Name'},
        {name: 'LastName', desc: 'Last Name'},
        {name: 'EmailAddress', desc: 'Email Address'},
        {name: 'Question1', desc: 'Question 1'},
        {name: 'Question2', desc: 'Question 2'},
        {name: 'Question3', desc: 'Question 3'},
        {name: 'Question4', desc: 'Question 4'},
        {name: 'Question5', desc: 'Question 5'},
        {name: 'Question6', desc: 'Question 6'}
    ];
    
    // Dialog message for when an invalid field is found
    var alertMsg = 'Please complete the following fields:\
\
';
    var length = alertMsg.length;
    var checked = [];
    
    for(var i = 0; i < requiredFields.length; i++) {
        var obj = form.elements[requiredFields[i].name];
        
        if (typeof obj !== 'undefined') {
            switch(obj.type) {
                // Textbox and textarea
                case 'text':
                case 'textarea':
                    if (inArray(['null', null], obj.value) || obj.value.length == 0) {
                        alertMsg += '- ' + requiredFields[i].desc + '\
';
                    }
                break;
                
                // Checkboxes and radio buttons
                case 'checkbox':
                case 'radio':
                    checked[requiredFields[i].name] = 0;
                    
                    // Loop through the checkboxes/radio buttons and increment
                    // a count if they are checked/selected
                    if (requiredFields[i]['name'].match(/([a-zA-Z0-9-_]+)\\[\\]/i)) {
                        for(var j = 0; j < obj.length; j++) {
                            if (obj[j].checked) checked[requiredFields[i].name]++;
                        }
                    } else {
                        if (obj.checked) checked[requiredFields[i].name]++;
                    }
                    
                    // Make sure that if a minimum check amount exists that the
                    // total checked count exceeds it
                    if (requiredFields[i].min > 0 && checked[requiredFields[i].name] < requiredFields[i].min) {
                        alertMsg += '- ' + requiredFields[i].desc + '\
';
                    }
                break;
            }
        }
    }
    
    // If the original length of error messages has grown
    // force an alert window upon the user
    if (alertMsg.length != length) {
        alert(alertMsg);
        return false;
    }
}
//]]>
</script>
</head>
<body>

<?php

if (isset($insertMsg)) {
    echo $insertMsg . '<br />';
}

?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return formCheck(this);" name="formcheck">
    <table width="300">
        <tbody>
            <tr>
                <th>First Name:</th>
                <td><input type="text" name="FirstName" size="25" value="<?php echo isset($firstname) ? $firstname : '' ?>" /></td>
            </tr>
            <tr>
                <th>Last Name:</th>
                <td><input type="text" name="LastName" size="25" value="<?php echo isset($lastname) ? $lastname : '' ?>" /></td>
            </tr>
            <tr>
                <th>E-mail Address:</th>
                <td><input type="text" name="EmailAddress" size="25" value="<?php echo isset($emailaddress) ? $emailaddress : '' ?>" /></td>
            </tr>
            <tr>
                <th>Question 1:</th>
                <td><input type="text" name="Question1" size="25" value="<?php echo isset($question1) ? $question1 : '' ?>" /></td>
            </tr>
            <tr>
                <th>Question 2:</th>
                <td><input type="text" name="Question2" size="25" value="<?php echo isset($question2) ? $question2 : '' ?>" /></td>
            </tr>
            <tr>
                <th>Question 3:</th>
                <td><input type="text" name="Question3" size="25" value="<?php echo isset($question3) ? $question3 : '' ?>" /></td>
            </tr>
            <tr>
                <th>Question 4:</th>
                <td><input type="text" name="Question4" size="25" value="<?php echo isset($question4) ? $question4 : '' ?>" /></td>
            </tr>
            <tr>
                <th>Question 5:</th>
                <td><input type="text" name="Question5" size="25" value="<?php echo isset($question5) ? $question5 : '' ?>" /></td>
            </tr>
            <tr>
                <th>Question 6:</th>
                <td><input type="text" name="Question6" size="25" value="<?php echo isset($question6) ? $question6 : '' ?>" /></td>
            </tr>
            <tr>
                <th>Additions:</th>
                <td><input type="text" name="Additions" size="25" value="<?php echo isset($additions) ? $additions : '' ?>" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit Form" name="submit" /></td>
            </tr>
        </tbody>
    </table>
</form>

</body>
</html>