Jump to content

Validation Help


dfowler

Recommended Posts

Hey guys, I have done simple javascript validation many times.  However, I am puzzled at the logic for what I need to do now.  Basically, there are a set of fields allowing somebody filling out the form to add options as they signup.  Each of these divs are hidden however, as it isn't required for somebody to add anything.  However, if somebody does type something in at least one of the fields; its counter must also have something in it.  Here is the code for the form:

<!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>Step 2 - Customer Information</title>
<script type="text/javascript">
/****VALIDATE REQUIRED FIELDS****/
function validateStep() {
if(document.form1.custFirstName.value == ""){
	alert("Please enter the customer's First Name.");
	document.form1.custFirstName.focus();
	return false;
}
if(document.form1.custLastName.value == ""){
	alert("Please enter the customer's Last Name.");
	document.form1.custLastName.focus();
	return false;
}
if(document.form1.compAddress.value == ""){
	alert("Please enter the customer's Company Address.");
	document.form1.compAddress.focus();
	return false;
}
if (document.form1.compCity.value == "") {
	alert("Please enter a City.");
	document.form1.compCity.focus();
	return false;
} // endif

if (document.form1.compState.value == "") {
	alert("Please enter a State.");
	document.form1.compState.focus();
	return false;
} // endif

if (document.form1.compPostalCode.value == "") {
	alert("Please enter a Zip/Postal Code.");
	document.form1.compPostalCode.focus();
	return false;
} // endif

if (document.form1.compCountry.value == "NONE") {
	alert("Please choose a Country.");
	document.form1.compCountry.focus();
	return false;
} // endif
if (document.form1.custPhone.value == "") {
	alert("Please enter a Phone Number.");
	document.form1.custPhone.focus();
	return false;
}
reValidPhone = /^[0-9]{3}-*[0-9]{3}-*[0-9]{4}$/;
if (!(reValidPhone.test(document.form1.custPhone.value))) {
	alert("Please enter the customer's phone number in the following format nnn-nnn-nnnn");
	document.form1.custPhone.focus();
	return false;
} // endif
if(document.form1.custEmail.value == ""){
	alert("Please enter the customer's email address.");
	document.form1.custEmail.focus();
	return false;
}
reValidEmail = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
if(!(reValidEmail.test(document.form1.custEmail.value))){
	alert("Please enter a valid email address.");
	document.form1.custEmail.focus();
	return false;
}
}

/****TOGGLE DIVS****/
var nextDiv = 1;
function showNext() {
var id = 'option[' + nextDiv + ']';
document.getElementById(id).style.display = 'block';
document.getElementById(id).scrollIntoView(true);
nextDiv++; // increment for next
}
</script>
</head>
<body>
  <form class="nobottomgap" id="form1" name="form1" method="post" action="step3.php" onSubmit="javascript: return validateStep();">
    <table width="100%" border="0">
      <tr>
        <td colspan="3">
          <span class="bodytxtorangebold">Customer Information:</span>
        </td>
      </tr>
      <tr>
        <td width="20%">
          <label>First/Last Name:</label>
        </td>
        <td>
          <input type="text" name="custFirstName" size="12" maxlength="20" value="<?php if(isset($_SESSION['custFirstName'])) { echo $_SESSION['custFirstName']; } ?>" /> 
          <input type="text" name="custLastName" id="custLastName" size="16" maxlength="20" value="<?php if(isset($_SESSION['custLastName'])) { echo $_SESSION['custLastName']; } ?>" />
        </td>
      </tr>
      <tr>
        <td>
          Company Name:
        </td>
        <td>
          <input type="text" name="compName" maxlength="40" value="<?php if(isset($_SESSION['compName'])) { echo $_SESSION['compName']; } ?>" />
        </td>
      </tr>
      <tr>
        <td>
          <label>Address:</label>
        </td>
        <td colspan="2">
          <input type="text" name="compAddress" size="50" value="<?php if(isset($_SESSION['compAddress'])) { echo $_SESSION['compAddress']; } ?>" />
        </td>
      </tr>
      <tr>
        <td>
          <label id="billcity1">City/State/Postal Code:</label>
        </td>
        <td>
          <input type="text" name="compCity" size="16" value="<?php if(isset($_SESSION['compCity'])) { echo $_SESSION['compCity']; } ?>" />
          <input type="text" name="compState" maxlength="20" size="2"  value="<?php if(isset($_SESSION['compState'])) { echo $_SESSION['compState']; } ?>" />
          <input type="text" name="compPostalCode" size="5" value="<?php if(isset($_SESSION['compPostalCode'])) { echo $_SESSION['compPostalCode']; } ?>" />
        </td>
      </tr>
      <tr>
        <td>
          <label>Country:</label>
        </td>
        <td colspan="2">
          <select name="compCountry" size="1">
            <option value="NONE"></option>
            <?php if(isset($_SESSION['compCountry'])) {
              if($_SESSION['compCountry'] == 'US') {
            ?>
              <option value="CA">Canada</option>
              <option value="US" selected>United States</option>
            <?php } else { ?>
              <option value="CA" selected>Canada</option>
              <option value="US">United States</option>
            <?php
              } 
            } else { 
            ?>
              <option value="CA">Canada</option>
              <option value="US">United States</option>
            <?php } ?>
          </select>
        </td>
      </tr>
      <tr>
        <td>
          <label>Phone:</label>
        </td>
        <td>
          <input type="text" name="custPhone" maxlength="12" size="15" value="<?php if(isset($_SESSION['custPhone'])) { echo $_SESSION['custPhone']; } ?>" /> (555-555-5555)
        </td>
      </tr>
      <tr>
        <td>
          <label>Email:</label>
        </td>
        <td colspan="2">
          <input type="text" name="custEmail" size="30" value="<?php if(isset($_SESSION['custEmail'])) { echo $_SESSION['custEmail']; } ?>" />
        </td>
      </tr>
    </table>
    <hr />
    <table width="100%" border="0">
      <tr>
        <td colspan="3">
          <span class="bodytxtorangebold">Options (max 10):</span>
        </td>
      </tr>
      <tr>
        <td colspan="3">
        <?php for ($i = 1; $i <= 10; $i++) { ?>
          <div id="option[<?=$i?>]" style="display: none">
            <table>
              <tr>
                <td width="20%">
                  <label>Option #<?php echo $i; ?>:</label>
                </td>
                <td colspan="2">
                  <input type="text" name="option[<?=$i?>]" size="12" maxlength="20" value="<?php if(isset($_SESSION['option'][$i])) { echo $_SESSION['option'][$i]; } ?>" />
                </td>
                </tr>
                <tr>
                <td>
                  <label>Description:</label>
                </td>
                <td colspan="2">
                  <input type="text" name="desc[<?=$i?>]" size="30" value="<?php if(isset($_SESSION['desc'][$i])) { echo $_SESSION['desc'][$i]; } ?>" />
                </td>
              </tr>
            </table>
            <hr />
          </div>
        <?php } ?>
        </td>
      </tr>
      <tr>
        <td>
          <a href="#" onclick="showNext(); return false;">Add Another Option</a>
        </td>
      </tr>
    </table>
  </form>
</body>
</html>

So if somebody clicks "Add Another Option" but doesn't fill anything out that is fine.  However, if the put an "a" in 'Option #' the form won't submit unless there is something in it's 'Description' and vice versa.  Make sense?

 

Thanks for any help!

Link to comment
Share on other sites

Could you not break down the code at all?

Ok, I guess the divs are all you really need.  Here is the code that creates the hidden divs:

<?php for ($i = 1; $i <= 10; $i++) { ?>
          <div id="option[<?=$i?>]" style="display: none">
            <table>
              <tr>
                <td width="20%">
                  <label>Option #<?php echo $i; ?>:</label>
                </td>
                <td colspan="2">
                  <input type="text" name="option[<?=$i?>]" size="12" maxlength="20" value="<?php if(isset($_SESSION['option'][$i])) { echo $_SESSION['option'][$i]; } ?>" />
                </td>
                </tr>
                <tr>
                <td>
                  <label>Description:</label>
                </td>
                <td colspan="2">
                  <input type="text" name="desc[<?=$i?>]" size="30" value="<?php if(isset($_SESSION['desc'][$i])) { echo $_SESSION['desc'][$i]; } ?>" />
                </td>
              </tr>
            </table>
            <hr />
          </div>
        <?php } ?>

Link to comment
Share on other sites

I tried this, but it isn't working:

for(i=1;i<11;i++) {
  if(option[i] != "") {
    if(document.form1.desc[i].value == "") {
      alert("Please fill out all required information.");
      document.form1.desc[i].focus();
      return false;
    }
  }
  if(desc[i] != "") {
    if(document.form1.option[i].value == "") {
      alert("Please fill out all required information.");
      document.form1.option[i].focus();
      return false;
    }
  }
}

Link to comment
Share on other sites

Try changing the field names to not have a numerical index. The PHP processing page will give them unique indexes as long as they are named as arrays. The probelm you are facing is that you cannot reference these arrays in Javascript the same way you would in PHP.

 

So, name your fields like this:

 name="option[]" 
name="desc[]" 

 

Then give this a try (Google XOR operator for more info.)

var df = document.form1;

for(i=1; i<11; i++)
{
  if (df['option[]'][i].value XOR df['desc[]'][i].value)
  {
    alert("Please fill out all required information.");
    df['option[]'][i].focus();
    return false;
  }
}

Link to comment
Share on other sites

Try changing the field names to not have a numerical index. The PHP processing page will give them unique indexes as long as they are named as arrays. The probelm you are facing is that you cannot reference these arrays in Javascript the same way you would in PHP.

 

So, name your fields like this:

 name="option[]" 
name="desc[]" 

 

Then give this a try (Google XOR operator for more info.)

var df = document.form1;

for(i=1; i<11; i++)
{
  if (df['option[]'][i].value XOR df['desc[]'][i].value)
  {
    alert("Please fill out all required information.");
    df['option[]'][i].focus();
    return false;
  }
}

The only problem I might see is on the page where I process the form.  Here is the code for that:

foreach($_POST['option'] as $k => $v) {
  if($v) {
    $_SESSION['option'][$k] = $_POST['option'][$k];
    $_SESSION['desc'][$k] = $_POST['desc'][$k];

    $query = "INSERT INTO customer_options (
	firstName,
	lastName,
	customerID
) values (
	'".addslashes($_POST['option'][$k])."', 
	'".addslashes($_POST['desc'][$k])."', 
	'".addslashes($_SESSION['customerID'])."'
)";
    $result = mysql_query($query) or die (mysql_error());
  }
}

As you have pointed out, PHP is what I know.  I pretty much do a lot of guessing with Javascript.  :)

Link to comment
Share on other sites

If you "know" PHP then you should know that you do not need to give the array fields a numerical index - PHP will do that for you. Your script should work just fine - although it could use some edits to make it more efficient and secure.

 

Note sure what this is supposed to do

if($v) {

 

If you are checking to see if that field has a non empty string value there are better ways to check that. That test would be problematic if the user accidentally entered spaces into that field. Also, you are doing absolutely no validation of the input on the server-side. You should never rely on javascript for validation. It is a nice feature to add for the user, but all validation must be done on the server-side and only optionally added to the client side.

 

//Create an array to hold all the records until the INSERT
$records = array();

foreach($_POST['option'] as $key => $option)
{
    //Remove leading/trailing spaces
    $option      = trim($option);
    $description = trim($_POST['desc'][$key]);

    //Only process if both fields have a value
    //Add error handling if you wish if only one has a value
    if(!empty($option) && !empty($description))
    {
        $_SESSION['option'][$key] = $option;
        $_SESSION['desc'][$key]   = $description;

        $option_SQL = mysql_real_escape_string();
        $description_SQL = mysql_real_escape_string();
        $customerID_SQL = mysql_real_escape_string();

        //Add new record to records array so only 1 query needs to be run
        $records[] = "('{$option_SQL}', '{$description_SQL}', '{$customerID_SQL}')"
  }
}

//Check if there are any records to add
if (count($records)>0)
{
    //Create one query will ALL the records to add
    $query = "INSERT INTO customer_options
              (firstName, lastName, customerID)
              values" . implode(",\n", $records);
    $result = mysql_query($query) or die (mysql_error());
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.