Hello All,
I'm creating a contact form for a company and i'm hitting a wall!

The form is working and all, but i can't seem to get the validation working properly.

I'd like to be able to require that the name is given and also EITHER a phone number OR email address.

My knowledge of javascript (and php for that matter) is pretty weak, but i've been able to get the form to erquire phone or email be entered... the problem is you can submit this form without entering a name as long as you enter an email or phone number...

What am i missing?

<?php
	if (!isset($_POST['sendMeNow'])) {
?>

<html>
<head>
<script type="text/javascript">

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function checkPhoneEmail() {
  if((document.getElementById('email').value=='' || document.getElementById('email').value==null) && (document.getElementById('phone').value=='' || document.getElementById('phone')==null)) {
     alert("You must fill in a contact mehod: Phone or Email");
     return false;
  }
  else { return true; }
}
</script>
</head>
<body>
            <form name="contact" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
				<table width="550" cellpadding="2" cellspacing="2">
					<tr>
						<td><select name="serviceCenter" onchange="document.contact.submit();">
								<option>Select Location</option>
								<option value="Location 1" <?php if ($_REQUEST['serviceCenter'] == 'Location 1') {echo 'selected="selected"';}?>>Location 1</option>
								<option value="Location 2" <?php if ($_REQUEST['serviceCenter'] == 'Location 2') {echo 'selected="selected"';}?>>Location 2</option>
								<option value="Location 3" <?php if ($_REQUEST['serviceCenter'] == 'Location 3') {echo 'selected="selected"';}?>>Location 3</option>
							</select></td>
						<td>&nbsp;</td>
						<td>&nbsp;</td>
						<td>&nbsp;</td>
					</tr>
				</table>
			</form>	
<?php
	switch ($_REQUEST['serviceCenter']) { //check serviceCenter value
		case 'Location 1': 
?>		
	<div id="google-map">
		<!-- insert map code here -->
	</div>	
	<div id="location-info">
	<!-- location information here -->
	</div>
	<br />	
<?php break;
		case 'Location 2': //if the value is Warren, MI then display the map
?>
	<div id="google-map">
		<!-- insert map code here -->
	</div>	
	<div id="location-info">
	<!-- location information here -->
	</div>
	<br />
<?php break;
		case 'Location 3':
?>
	<div id="google-map">
		<!-- insert map code here -->
	</div>	
	<div id="location-info">
	<!-- location information here -->
	</div>
	<br />	
<?php break;
		default:
?>
<br />
<?php
}
?>		
			<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST"  onsubmit="return checkPhoneEmail()">		
				<table width="550" cellpadding="2" cellspacing="2">	
					<tr>
						<td>Name:</td>
						<td><input type="text" name="name" /></td>
						<td>&nbsp;</td>
						<td>&nbsp;</td>
					</tr>
					<tr>
						<td>Email:</td>
						<td><input type="text" name="email" id="email" /></td>
						<td>&nbsp;</td>
						<td>&nbsp;</td>
					</tr>
					<tr>
						<td>Phone:</td>
						<td><input type="text" name="phone" id="phone" maxlength="10" /></td>
						<td>&nbsp;</td>
						<td>&nbsp;</td>
					</tr>
					<tr>
						<td>Message:</td>
						<td><textarea name="message" cols="40" rows="7"></textarea></td>
						<td>&nbsp;</td>
						<td>&nbsp;</td>
					</tr>
					<tr>
						<td>&nbsp;</td>
						<td><input type="submit" name="sendMeNow" value="Submit" onClick="MM_validateForm('name','','R','email','','NisEmail','phone','','NisNum');return document.MM_returnValue" />&nbsp;&nbsp;&nbsp;<input type="reset" name="reset" value="Reset" /></td>
						<td>&nbsp;</td>
						<td>&nbsp;</td>
					</tr>																																																		
				</table>															

		</form>

</body>
</html>

<?php

}	else {

$name=$_REQUEST['name'];
$phone = stripslashes($_REQUEST['phone']);
$email = $_REQUEST['email'];
$location = $_REQUEST['serviceCenter'];
$serviceCheck = '';
	foreach ($_REQUEST['serviceType'] as $value) {
		$serviceCheck .= "\n    $value";
	}
$message = $_REQUEST['message'];


	switch ($_REQUEST['serviceCenter']) {
		case 'Location 1':
			$to = "location1@store.net";
		break;
		case 'Location 2':
			$to = "location2@store.net";
		break;
		case 'Location 3':
			$to = "location3@store.net";
		break;
		default:
			$to = "location1@store.net";
		break;
	}	

$msg = "You have received a message from your website's 'Contact Page'. The information the visitor submitted can be seen below:\n\n\n\nContact Information\n\nName: $name\nPhone: $phone\nEmail: $email\n\nService Requested: $serviceCheck\n\nMessage:\n$message";

mail("$to", "Contact from the website", "$msg", "From: $email");			

?>
<html>
<head></head>
<body>
	Thank you...
</body>
</html>
<?php
}
?>

Thanks in advance all!

    It seems as if you are using the built-in Dreamweaver Scripts.

    I would recommend looking at the w3schools page on JS Form Validation Here.

    Although isn't bulletproof it works quite well most of the time.

    It is also worth mentioning to check if values have been submitted within your PHP code as well, if someone has JS turned off and some bots ignore JS, it is always good to validate with PHP as well.

    [edit]
    I forgot to mention...

    function validate_form(thisform)
    {
    with (thisform)
      {
      if ((validate_required(email,"Email must be filled out!")==false) && (validate_required(name,"Name must be filled out!")==false) && (validate_required(phone,"Phone must be filled out!")==false))
      {
      email.focus();return false;
      }
      }
    }
    

    This is a horrible answer as it will focus on the email nomatter what.

    You can play with the code to not return false unless all 3 are false.
    [/edit]

    I hope this helps...

      Ya, that is way over-complicated...

      I typically check the length of something to avoid doing "document.getElementById('id').innerHTML == ''".

        Thanks Big Nerd!

        I'm going to start working through their tutorials tomorrow to try to get a better grasp of this..

        As far as validating with php... how would you go about doing this? I know how to check to see if fields were submitted, but i havne't used both forms of validation before... do you have any tips that could point me in the right direction?

        I would think the php would check to see if the fields were filled out only after the form is submitted... if this is the case, at what point would the javascript be called?

        Sorry if i'm talking in circles :-)

          MainStWebGuy;10916911 wrote:

          Thanks Big Nerd!

          I'm going to start working through their tutorials tomorrow to try to get a better grasp of this..

          As far as validating with php... how would you go about doing this? I know how to check to see if fields were submitted, but i havne't used both forms of validation before... do you have any tips that could point me in the right direction?

          I would think the php would check to see if the fields were filled out only after the form is submitted... if this is the case, at what point would the javascript be called?

          Sorry if i'm talking in circles :-)

          Where you send the action from the form to, do this:

          if (isset($_POST['whateverYourSubmitIsCalled']))
          {
               // do validation
          }
          

          You would generally put this before all other code. Note that there are many different ways for PHP validation. Take a look here.

          Some of the validation functions might be something like this:

          function escapeData($data, mysqli $connection)
          {
               return mysqli_real_escape_string($connection, $data);
          }
          

          or

          function deepEscape($data, mysqli $connection)
          {
               return mysqli_real_escape_string($connection, strip_tags(addslashes($data)));
          }
          

            Exactly what Swamp56 said.

            I would add some predefined checks, such as the name length is at least two char's

            $error = array();
            if (isset($_POST['whateverYourSubmitIsCalled']))
            {
                 $name = deepEscape($_POST['name'],$connection);
                 if (strlen($name) <= 1) {
                      $error[] = "Name Much be more than one char";
                 }
                 // do validation
            } 
            
            if (sizeof($error) > 0) {
              foreach($error as $problem) {
                echo $problem."<br />";
              }
            
            }
            

            This is a very basic (again) example, you could search Google for other methods of validation, however i'd recommend string length as its the easiest, such as a phone number is at least 7 char's.

            If they have entered nothing at all (thus is less than 2 chars on name) it can return an error.

              Write a Reply...