Form validation help!

This is a discussion on "Form validation help!" within the JavaScript Forum section. This forum, and the thread "Form validation help! are both part of the Program Your Website category.



Go Back   Webforumz.com > Main Forums > Program Your Website > JavaScript Forum

Notices


Reply
 
LinkBack Thread Tools
  #1 (permalink)  
Old Feb 9th, 2008, 19:09
Junior Member
Join Date: Feb 2008
Location: England
Age: 21
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Form validation help!

I need some help with a form that has 2 text box entries, I tried making the validation from each into separate functions then calling both functions from the one that is called upon on the onsubmit function, but i can't seem to get it to work as it just seems to go ahead with the submit as usual with no validating going on.

Code: Select all
<?php
include "connect_details.php";
?>

<html>
<head>
<title>Clothing Line</title>
<link href="stylesheetCL.css" rel="stylesheet">
<?php require('jscript.inc') ?>

<script language='JavaScript' type='text/JavaScript'>
<!--

function Validate(f)
{
   var f1 = ValCampusName(f)
   var f2 = ValCampusEmail(f)

   if (f1 && f2) 
   { 
      return true
   } 
   else 
   { 
      return false
   }
}

function ValCampusName(f)
{
   if(document.getElementById('Campus').value.length<1)
   {
      document.getElementById('Campus').focus();
      document.getElementById('mySpan1').innerHTML='Please Enter the Campus Name!';
      return false
   }
   else
   {
      return true
   }

}

function ValCampusEmail(f) 
{
   var emailRegxp = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
   var emailAddress = document.getElementById('CampusEmail').value;

   if(emailAddress.length < 5 || emailRegxp.test(emailAddress) != true) 
   {
      document.getElementById('CampusEmail').focus();
      document.getElementById('mySpan1').innerHTML='Please Enter a Valid Campus Email!';
      return false;
   }
   else
   {
   return true;
   }
}

//-->
</script>   

</head>
<body>

<?php require('header.inc') ?>
<?php require('menu.inc') ?>

<div style="position:absolute; top:5px; left:200px; width:550px">

<span class="head3">New Campus Form</span><br><br>
  
<form method="POST" action="add_campus_details_php.php" name="AddCampus" onsubmit="return Validate(this);">

<span id="mySpan1" class="errmsg"></span><br>
Campus Name: <input type="text" name="Campus"/><br><br>

<span id="mySpan2" class="errmsg"></span><br>   
Campus Email: <input type="text" size="45" name="CampusEmail"/><br><br>


<input type="submit" name="SubmitB" value="Submit"/>
</form>  
<br><br><br><br>

<a href="display_campus_details.php?Action=Edit">Back to Edit Campus Details List</a>
</div>

</body>
</html>
Reply With Quote

  #2 (permalink)  
Old Feb 10th, 2008, 10:18
spinal007's Avatar
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 22
Posts: 1,619
Blog Entries: 1
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via ICQ to spinal007 Send a message via MSN to spinal007 Send a message via Yahoo to spinal007 Send a message via Skype™ to spinal007
Re: Form validation help!

use "alert" to debug and find out what the real output of the validation function is:

onsubmit="alert(Validate(this)); return false;"

It needs to be false if you want to interrupt form submission.
Last Blog Entry: Random String in Javascript (Apr 21st, 2008)
Reply With Quote
  #3 (permalink)  
Old Feb 10th, 2008, 18:04
Junior Member
Join Date: Feb 2008
Location: England
Age: 21
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

I just tried that but for some reason it just completely ignored the Javascript and even the alert to just submit anyway. I do not have javascript disabled on my browser as my other form (with 1 text box entry) works just fine, but the main problem was trying to get it to work with multiple form entries and functions.

Heres the code atm
Code: Select all
<?php
include "connect_details.php";
?>

<html>
<head>
<title>Clothing Line</title>
<link href="stylesheetCL.css" rel="stylesheet">
<?php require('jscript.inc') ?>

<script language='JavaScript' type='text/JavaScript'>
<!--

function ValCampusName(elem)
{
   if(document.getElementById('Campus').value.length<1)
   {
      document.getElementById('Campus').focus();
      document.getElementById('mySpan1').innerHTML='Please Enter the Campus Name!';
      return false
   }
   else
   {
      return true
   }

}

function ValCampusEmail(elem) 
{
   var emailRegxp = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
   var emailAddress = document.getElementById('CampusEmail').value;

   if(emailAddress.length < 5 || emailRegxp.test(emailAddress) != true) 
   {
      document.getElementById('CampusEmail').focus();
      document.getElementById('mySpan1').innerHTML='Please Enter a Valid Campus Email!';
      return false;
   }
   else
   {
   return true;
   }
}

function Validate(form)
{
   var Errors = ""; 
   Errors += ValCampusName(form.Campus.value);
   Errors += ValCampusEmail(form.CampusEmail.value);

   if (Errors != "") 
   { 
      return false
   } 
   else 
   { 
      return true
   }
}
//-->
</script>   

</head>
<body>

<?php require('header.inc') ?>
<?php require('menu.inc') ?>

<div style="position:absolute; top:5px; left:200px; width:550px">

<span class="head3">New Campus Form</span><br><br>
  
<form method="POST" action="add_campus_details_php.php" name="AddCampus" onsubmit="alert(Validate(this)); return false;">

<span id="mySpan1" class="errmsg"></span><br>
Campus Name: <input type="text" name="Campus"/><br><br>

<span id="mySpan2" class="errmsg"></span><br>   
Campus Email: <input type="text" size="45" name="CampusEmail"/><br><br>

<input type="submit" name="SubmitB" value="Submit"/>
</form>  
<br><br><br><br>

<a href="display_campus_details.php?Action=Edit">Back to Edit Campus Details List</a>
</div>

</body>
</html>
Reply With Quote
  #4 (permalink)  
Old Feb 10th, 2008, 19:07
Junior Member
Join Date: Jul 2007
Location: Los Angeles
Age: 31
Posts: 28
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

You should really use the form object and not 'gtElementById'

The following would go on the form:

onsubmit="validateMe(this);"

and the function example:

HTML: Select all
function validateMe(theForm) {
 
var msg = "The following fields were left blank:\n\n";
var msg2 = "The following error(s) have occurred:\n\n";
var error = false;
var error2 = false;
 
if (theForm.contact.value == "") {
error = true
msg += " - Contact Person\n";
}
 
if (theForm.email.value == "") {
error = true
msg += " - E-mail\n";
} else if (!theForm.email.value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)) {
error2 = true
msg2 += " - Enter a valid email address\n";
} else if (theForm.email.value !== theForm.conf_email.value) {
error2 = true
msg2 += " - Re-confirm your email address\n";
}
 
if (error && !error2) {
alert(msg);
return false;
} else if (!error && error2) {
alert(msg2);
return false;
} else if (error && error2) {
alert(msg + "\n\n" + msg2)
return false;
} else {
return true;
}
}
The function handles both fields left blank and those where the data format was invalid

Last edited by c010depunkk; Feb 11th, 2008 at 10:02. Reason: please use [HTML] when posting HTML
Reply With Quote
  #5 (permalink)  
Old Feb 10th, 2008, 23:16
Junior Member
Join Date: Feb 2008
Location: England
Age: 21
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

The thing is I don't want it alerting (pop-ups) and just have a clear message on the form above the value that is incorrect. I have made a few modifications based on my previous form with javascript validation and my previous version of this form using server-side validation so that both are involved in case Javascript is disabled.

What happens now is that the javascript error messages appear, then the form submits regardless and my php validation kicks in to stop it so replaces the error messages with it's own. So at least it's working partially.

Code: Select all
<?php
session_start();
include "connect_details.php";

$Submit = $_POST['SubmitB'];

//get current type selected

if ($_POST['SubmitB'] == "Submit")
{
   $Campus = $_POST['Campus'];
   $CampusEmail = $_POST['CampusEmail'];
   $ConfirmEmail = $_POST['ConfirmEmail'];

   $errors=0;
   $Valid_CampusID = true;
   $Valid_Campus = true;
   $Valid_CampusEmail = true;

   if(empty($Campus))
   {
      $errors++;
      $Valid_Campus = false;
      $Message_Campus = "Please Enter the Campus Name (PHP)";
   }

   if (!preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $CampusEmail)) 
   {   
      $errors++;
      $Message_CampusEmail = "Please Enter a valid Campus Email Address (PHP)";          
   }
   elseif($CampusEmail != $ConfirmEmail)
   {
      $errors++;
      $Message_CampusEmail = "The Email Addresses do not match please re-confirm them (PHP)";         
   }

   if($errors==0)
   { 
      $conn = mysql_connect('mysql2.freehostia.com:3306','adacom_CLine','clothingline');
      $db = mysql_select_db('adacom_CLine', $conn);
      $sql = "SELECT CampusID,Campus,CampusEmail FROM Campus ORDER BY CampusID";
      $rs = mysql_query($sql, $conn)or die('Problem with query: ' . $sql . '<br />' . mysql_error());
      $NumberOfRecords = mysql_num_rows($rs);
      $CampusID = "Campus".($NumberOfRecords+1);
      $sqlNew = "INSERT INTO Campus (CampusID,Campus,CampusEmail) VALUES('$CampusID','$Campus','$CampusEmail')";
      $rsNew = mysql_query($sqlNew,$conn)or die('Problem with query: ' . $sqlNew . '<br />' . mysql_error());        

      if(mysql_affected_rows($conn) == 1)
      {
         $_SESSION['NewAction'] = "Added";
      }
      elseif(mysql_affected_rows($conn) == 0)
      {
         $_SESSION['NewAction'] = "NotAdded";      
      }
      mysql_close($conn);
   }
}

?>
<html>
<head>
<title>Clothing Line</title>
<link href="stylesheetCL.css" rel="stylesheet">
<?php require('jscript.inc') ?>
<script language='JavaScript' type='text/JavaScript'>
<!--

function Validate(f)
{
   Errors = 0
   Errors = Errors+ValidateValues(f)

   if (Errors == 0) 
   { 
      return true 
   } 
   else 
   { 
      return false 
   }

}

function ValidateValues(f)
{
   var Errors = 0
   
   if(f['Campus'].value.length<1)
   {
      document.getElementById('mySpan1').innerHTML='Please Enter an Item Type!';
      Errors = 1
   }

   if(f['CampusEmail'].value =="")
   {
      Errors = 1 
      document.getElementById('mySpan2').innerHTML='Please Enter an Email Address!';
   }
   elseif(!f['CampusEmail'].value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/))
   {
      Errors = 1
      document.getElementById('mySpan2').innerHTML='Please Enter a Valid Email Address!';
   }
   elseif(f['CampusEmail'].value !== f['ConfirmEmail'].value)
   {
      Errors = 1
      document.getElementById('mySpan2').innerHTML='The Email Addresses do not match, please re-confirm them!';
   }

   return Errors
}


//-->
</script> 
</head>
<body>

<?php require('header.inc') ?>
<?php require('menu.inc') ?>

<div style="position:absolute; top:5px; left:200px; width:550px">

<span class="head3">New Campus Form</span><br><br>
  
<form method="POST" action="add_campus_details_form.php" name="AddCampus" onsubmit="return Validate(this)">

<span id="mySpan1" class="errmsg"><?php echo $Message_Campus?></span><br>
Campus Name: <br><input type="text" name="Campus" value="<?php echo $Campus?>"/><br><br><br>

<span id="mySpan2" class="errmsg"><?php echo $Message_CampusEmail?></span><br>   
Campus Email: <br><input type="text" size="45" name="CampusEmail" value="<?php echo $CampusEmail?>"/><br><br>
Confirm Email Address: <br><input type ="text" size="45" name="ConfirmEmail" value="<?php echo $ConfirmEmail?>"/><br><br>

<input type="submit" name="SubmitB" value="Submit"/>
</form>  
<br><br><br><br>

<a href="display_campus_details.php?Action=Edit">Back to Edit Campus Details List</a>
</div>

</body>
</html>
Reply With Quote
  #6 (permalink)  
Old Feb 10th, 2008, 23:42
Junior Member
Join Date: Jul 2007
Location: Los Angeles
Age: 31
Posts: 28
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

If the form is still submitting you need to add:

return false;

If an error is found, or

return true;

If no error is found.
Reply With Quote
  #7 (permalink)  
Old Feb 10th, 2008, 23:48
Junior Member
Join Date: Feb 2008
Location: England
Age: 21
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

I've done this:

Code: Select all
function Validate(f)
{
   Errors = 0
   Errors = Errors+ValidateValues(f)
   
   if (Errors == 0) 
   { 
      return true; 
   } 
   else 
   { 
      return false; 
   }
}

function ValidateValues(f)
{
   Errors = 0
   
   if(f['Campus'].value.length<1)
   {
      document.getElementById('mySpan1').innerHTML='Please Enter an Item Type!';
      Errors = 1
   }

   if(f['CampusEmail'].value =="")
   {
      Errors = 1 
      document.getElementById('mySpan2').innerHTML='Please Enter an Email Address!';
   }
   elseif(!f['CampusEmail'].value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/))
   {
      Errors = 1
      document.getElementById('mySpan2').innerHTML='Please Enter a Valid Email Address!';
   }
   elseif(f['CampusEmail'].value !== f['ConfirmEmail'].value)
   {
      Errors = 1
      document.getElementById('mySpan2').innerHTML='The Email Addresses do not match, please re-confirm them!';
   }

   if (Errors == 0) 
   { 
      return true; 
   } 
   else 
   { 
      return false; 
   }
}

But it's still doing the same thing of submitting and showing both messages.
Reply With Quote
  #8 (permalink)  
Old Feb 11th, 2008, 03:45
spinal007's Avatar
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 22
Posts: 1,619
Blog Entries: 1
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via ICQ to spinal007 Send a message via MSN to spinal007 Send a message via Yahoo to spinal007 Send a message via Skype™ to spinal007
Re: Form validation help!

Quote:
The thing is I don't want it alerting
alert is good for debugging. it's one way of monitoring what;s going on in the script. once everything is working fine, take out the alerts....

Quote:
I just tried that but for some reason it just completely ignored the Javascript and even the alert to just submit anyway
You probably have an error in the script. If the browser encounters an error it will abort the onsubmit event and continue with the conventional form submission.

What browser are you using? Are you sure it's showing error messages?
In IE.: Tools > Options > Advanced > tick: Show notification about every script error
Firefox: Get Firebug

Instead of...
onsubmit="Validate(this);"

... a better implementation would be:
onsubmit="
try{
if(Validate(this)) this.submit();
}catch(e){}
return false;
"

This way the form will only submit if the script has no error AND it passes the validation. And if an error occurs, at least it will stay on the page so you can work out what the problem is...
Last Blog Entry: Random String in Javascript (Apr 21st, 2008)
Reply With Quote
  #9 (permalink)  
Old Feb 11th, 2008, 03:49
spinal007's Avatar
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 22
Posts: 1,619
Blog Entries: 1
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via ICQ to spinal007 Send a message via MSN to spinal007 Send a message via Yahoo to spinal007 Send a message via Skype™ to spinal007
Re: Form validation help!

this line...
f['Campus'].value.length
... will can cause an error in some browsers if the Campus field is empty. The value property doesn't always return a string (sometimes it's null) so you can;t call the 'length' property. A better approach would be...
(f['Campus'].value+'').length
...which makes sure we have a string before we call the length property.

Use firebug or alerts to report the progress of the script, step by step, and you will eventually work out where it breaks.
Last Blog Entry: Random String in Javascript (Apr 21st, 2008)
Reply With Quote
  #10 (permalink)  
Old Feb 11th, 2008, 03:51
spinal007's Avatar
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 22
Posts: 1,619
Blog Entries: 1
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via ICQ to spinal007 Send a message via MSN to spinal007 Send a message via Yahoo to spinal007 Send a message via Skype™ to spinal007
Re: Form validation help!

OK, ignore both of my previous posts.
I've just realised you've got it working...

the problem is that you have this:
onsubmit="validateMe(this);"
...when you should have...
onsubmit="return validateMe(this);"
...case closed.
Last Blog Entry: Random String in Javascript (Apr 21st, 2008)
Reply With Quote
  #11 (permalink)  
Old Feb 11th, 2008, 10:08
Junior Member
Join Date: Feb 2008
Location: England
Age: 21
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

Unfortunately I tried the method in post #10 already but it ignored the javascript altogether, the closest I got to getting it complete was using your script in #8 which did all the javascript validation and stopped the form submitting...even when all fields are filled out and didn't even let me retry the javascript when I pressed the submit again unless i refreshed the page.

Last edited by psycho wolvesbane; Feb 11th, 2008 at 10:15.
Reply With Quote
  #12 (permalink)  
Old Feb 11th, 2008, 15:27
spinal007's Avatar
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 22
Posts: 1,619
Blog Entries: 1
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via ICQ to spinal007 Send a message via MSN to spinal007 Send a message via Yahoo to spinal007 Send a message via Skype™ to spinal007
Re: Form validation help!

Quote:
Originally Posted by psycho wolvesbane View Post
even when all fields are filled out and didn't even let me retry the javascript when I pressed the submit again unless i refreshed the page.
Then an error has happened somewhere. Like I said:

Quote:
In IE.: Tools > Options > Advanced > tick: Show notification about every script error
Firefox: Get Firebug
Last Blog Entry: Random String in Javascript (Apr 21st, 2008)
Reply With Quote
  #13 (permalink)  
Old Feb 11th, 2008, 18:39
Junior Member
Join Date: Feb 2008
Location: England
Age: 21
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

I turned on the debugger in IE and it comes up with nothing. Also I installed Firebug but I have no idea how to debug with it, either that or it isn't coming up with anything either thus displays nothing useful.

Here's the current code for this annoying form:
Code: Select all
<?php
session_start();
include "connect_details.php";

$Submit = $_POST['SubmitB'];

if ($Submit == "Submit")
{
   $Campus = $_POST['Campus'];
   $CampusEmail = $_POST['CampusEmail'];
   $ConfirmEmail = $_POST['ConfirmEmail'];

   $Errors=0;
   $Valid_CampusID = true;
   $Valid_Campus = true;
   $Valid_CampusEmail = true;

   if(empty($Campus))
   {
      $Errors++;
      $Valid_Campus = false;
      $Message_Campus = "Please Enter the Campus Name (PHP)";
   }

   if (!preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $CampusEmail)) 
   {   
      $Errors++;
      $Message_CampusEmail = "Please Enter a valid Campus Email Address (PHP)";          
   }
   elseif($CampusEmail !== $ConfirmEmail)
   {
      $Errors++;
      $Message_CampusEmail = "The Email Addresses do not match please re-confirm them (PHP)";         
   }

   if($Errors==0)
   { 
      $conn = mysql_connect('mysql2.freehostia.com:3306','adacom_CLine','clothingline');
      $db = mysql_select_db('adacom_CLine', $conn);
      $sql = "SELECT CampusID,Campus,CampusEmail FROM Campus ORDER BY CampusID";
      $rs = mysql_query($sql, $conn)or die('Problem with query: ' . $sql . '<br />' . mysql_error());
      $NumberOfRecords = mysql_num_rows($rs);
      $CampusID = "Campus".($NumberOfRecords+1);
      $sqlNew = "INSERT INTO Campus (CampusID,Campus,CampusEmail) VALUES('$CampusID','$Campus','$CampusEmail')";
      $rsNew = mysql_query($sqlNew,$conn)or die('Problem with query: ' . $sqlNew . '<br />' . mysql_error());        

      if(mysql_affected_rows($conn) == 1)
      {
         $_SESSION['NewAction'] = "Added";
      }
      elseif(mysql_affected_rows($conn) == 0)
      {
         $_SESSION['NewAction'] = "NotAdded";      
      }
      mysql_close($conn);
      $Cont = true;
   }
}

?>
<html>
<head>
<title>Clothing Line</title>
<link href="stylesheetCL.css" rel="stylesheet">
<?php require('jscript.inc');

if($Cont == true)
{
   echo"<meta HTTP-EQUIV='REFRESH' content='0; url=display_campus_details.php?Action=Edit'>";
}
?>

<script language='JavaScript' type='text/JavaScript'>
<!--

function Validate(f)
{
   Errors = 0
   Errors = Errors+ValidateValues(f)
   
   if (Errors == 0) 
   { 
      return true; 
   } 
   else 
   { 
      return false; 
   }
}

function ValidateValues(f)
{
   Errors = 0
   
   if((f['Campus'].value+'').length<1)
   {
      document.getElementById('mySpan1').innerHTML='Please Enter a Campus Name!';
      Errors = 1
   }

   if(f['CampusEmail'].value =="")
   {
      Errors = 1 
      document.getElementById('mySpan2').innerHTML='Please Enter an Email Address!';
   }
   elseif(!f['CampusEmail'].value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/))
   {
      Errors = 1
      document.getElementById('mySpan2').innerHTML='Please Enter a Valid Email Address!';
   }
   elseif(f['CampusEmail'].value !== f['ConfirmEmail'].value)
   {
      Errors = 1
      document.getElementById('mySpan2').innerHTML='The Email Addresses do not match, please re-confirm them!';
   }

   if (Errors == 0) 
   { 
      return true; 
   } 
   else 
   { 
      return false; 
   }
}


//-->
</script> 
</head>
<body>

<?php //require('header.inc') ?>
<?php require('menu.inc') ?>

<div style="position:absolute; top:5px; left:200px; width:550px">

<span class="head3">New Campus Form</span><br><br>
  
<form method="POST" action="add_campus_details_form.php" name="AddCampus" onSubmit="try{if (Validate(this)) this.submit();}catch(e){}return false;">

<span id="mySpan1" class="errmsg"><?php echo $Message_Campus?></span><br>
Campus Name: <br><input type="text" name="Campus" value="<?php echo $Campus?>"/><br><br><br>

<span id="mySpan2" class="errmsg"><?php echo $Message_CampusEmail?></span><br>   
Campus Email: <br><input type="text" size="45" name="CampusEmail" value="<?php echo $CampusEmail?>"/><br><br>
Confirm Email Address: <br><input type ="text" size="45" name="ConfirmEmail" value="<?php echo $ConfirmEmail?>"/><br><br>

<input type="submit" name="SubmitB" value="Submit"/>
</form>  
<br><br><br><br>

<a href="display_campus_details.php?Action=Edit">Back to Edit Campus Details List</a>
</div>

</body>
</html>
And here is the form that works but only has 1 text input:

Code: Select all
<?php
session_start(); 
include "connect_details.php";

$Errors = 0;
$Submit = $_POST['SubmitB'];
$ItemType = $_POST['ItemType'];


if ($_POST['SubmitB'] == "Submit")
{
   $Valid_ItemType = true;
     
   if ($ItemType == "")
   {

      $MessageItemType = "Please Enter an Item Type (php)";
 
      $Errors++;
      $Valid_ItemType = false;
   }
     
   if($Errors == 0)
   { 
      $conn = mysql_connect($Host,$Username,$Password) or die(mysql_error());
      $db = mysql_select_db($Dbname, $conn);
      $sqlNew = "INSERT INTO ItemType (ItemType) VALUES('$ItemType')";
      $rsNew = mysql_query($sqlNew,$conn)or die('Problem with query: ' . $sqlNew . '<br />' . mysql_error());        
    
      if(mysql_affected_rows($conn) == 1)
      {
         $_SESSION['NewAction'] = "Added";
      }
      elseif(mysql_affected_rows($conn) == 0)
      {
         $_SESSION['NewAction'] = "NotAdded";
      }
      mysql_close($conn);
      
      $Cont = true;
   }

}

?>

<html>
<head>
<title>New item Type Form</title>
<link href="stylesheetCL.css" rel="stylesheet">
<?php require('jscript.inc') ?>

<?php if($Cont == true)
{
   ?>
   <meta HTTP-EQUIV="REFRESH" content="0; url=display_item_types.php?Action=Edit">
   <?php
}
?>

<script language='JavaScript' type='text/JavaScript'>
<!--

function Validate(f)
{
   Errors = 0
   Errors = Errors + ValidateItemType(f)

   if (Errors == 0) 
   { 
      return true 
   } 
   else 
   { 
      return false 
   }
}

function ValidateItemType(f)
{
   if(f['ItemType'].value.length<1)
   {
      document.getElementById('mySpan1').innerHTML='Please Enter an Item Type!';
      Errors = 1
   }
   else
   {
      Errors = 0
   }
   return Errors
}

//-->
</script>
</head>
<body>


<?php require('header.inc') ?>

<?php require('menu.inc') ?>


<div style="position:absolute; top:5px; left:200px; width:550px">

<span class="head3">New Item Type Form</span><br><br>

<form method="POST" action="add_item_type_form.php" name="AddItemType" onsubmit="return Validate(this)">

<span id="mySpan1" class="errmsg"><?php echo $MessageItemType?></span><br>
Item Type: <input type="text" name="ItemType" value="<?php echo $ItemType?>"><br><br>
<input type="submit" name="SubmitB" value="Submit">

</form><br><br><br><br>

<a href="admin.php">Back to the Admin Menu</a>

</div>

</body>
</html>

Last edited by psycho wolvesbane; Feb 11th, 2008 at 18:46.
Reply With Quote
  #14 (permalink)  
Old Feb 11th, 2008, 22:50
spinal007's Avatar
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 22
Posts: 1,619
Blog Entries: 1
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via ICQ to spinal007 Send a message via MSN to spinal007 Send a message via Yahoo to spinal007 Send a message via Skype™ to spinal007
Re: Form validation help!

Can you upload this somewhere?
The code reads fine, I'm not sure about the way you're referring to the form elements though:f['CampusEmail'].value may not work in some browsers...
Last Blog Entry: Random String in Javascript (Apr 21st, 2008)
Reply With Quote
  #15 (permalink)  
Old Feb 11th, 2008, 23:01
Junior Member
Join Date: Feb 2008
Location: England
Age: 21
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

Okay I've uploaded it to: http://psychowolvesbane.freehostia.c...tails_form.php

The current code:

Code: Select all
<?php
session_start();
include "connect_details.php";

$Submit = $_POST['SubmitB'];

if ($_POST['SubmitB'] == "Submit")
{
   $Campus = $_POST['Campus'];
   $CampusEmail = $_POST['CampusEmail'];
   $ConfirmEmail = $_POST['ConfirmEmail'];

   $Errors=0;
   $Valid_CampusID = true;
   $Valid_Campus = true;
   $Valid_CampusEmail = true;

   if(empty($Campus))
   {
      $Errors++;
      $Valid_Campus = false;
      $Message_Campus = "Please Enter the Campus Name (PHP)";
   }

   if (!preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $CampusEmail)) 
   {   
      $Errors++;
      $Message_CampusEmail = "Please Enter a valid Campus Email Address (PHP)";          
   }
   elseif($CampusEmail !== $ConfirmEmail)
   {
      $Errors++;
      $Message_CampusEmail = "The Email Addresses do not match please re-confirm them (PHP)";         
   }

   if($Errors==0)
   { 
      $conn = mysql_connect('mysql2.freehostia.com:3306','adacom_CLine','clothingline');
      $db = mysql_select_db('adacom_CLine', $conn);
      $sql = "SELECT CampusID,Campus,CampusEmail FROM Campus ORDER BY CampusID";
      $rs = mysql_query($sql, $conn)or die('Problem with query: ' . $sql . '<br />' . mysql_error());
      $NumberOfRecords = mysql_num_rows($rs);
      $CampusID = "Campus".($NumberOfRecords+1);
      $sqlNew = "INSERT INTO Campus (CampusID,Campus,CampusEmail) VALUES('$CampusID','$Campus','$CampusEmail')";
      $rsNew = mysql_query($sqlNew,$conn)or die('Problem with query: ' . $sqlNew . '<br />' . mysql_error());        

      if(mysql_affected_rows($conn) == 1)
      {
         $_SESSION['NewAction'] = "Added";
      }
      elseif(mysql_affected_rows($conn) == 0)
      {
         $_SESSION['NewAction'] = "NotAdded";      
      }
      mysql_close($conn);
      $Cont = true;
   }
}

?>
<html>
<head>
<title>Clothing Line</title>
<link href="stylesheetCL.css" rel="stylesheet">
<?php require('jscript.inc');

if($Cont == true)
{
   echo"<meta HTTP-EQUIV='REFRESH' content='0; url=display_campus_details.php?Action=Edit'>";
}
?>

<script language='JavaScript' type='text/JavaScript'>
<!--

function Validate(f)
{
   Errors = 0
   Errors = Errors+ValidateValues(f)
   
   if (Errors == 0) 
   { 
      return true; 
   } 
   else 
   { 
      return false; 
   }
}

function ValidateValues(f)
{
   Errors = 0
   
   if((document.AddCampus.Campus.value+'').length<1)
   {
      document.getElementById('mySpan1').innerHTML='Please Enter a Campus Name!';
      Errors = 1
   }

   if(document.AddCampus.CampusEmail.value =="")
   {
      Errors = 1 
      document.getElementById('mySpan2').innerHTML='Please Enter an Email Address!';
   }
   elseif(!document.AddCampus.CampusEmail.value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/))
   {
      Errors = 1
      document.getElementById('mySpan2').innerHTML='Please Enter a Valid Email Address!';
   }
   elseif(document.AddCampus.CampusEmail.value !== document.AddCampus.ConfirmEmail.value)
   {
      Errors = 1
      document.getElementById('mySpan2').innerHTML='The Email Addresses do not match, please re-confirm them!';
   }

   if (Errors == 0) 
   { 
      return true; 
   } 
   else 
   { 
      return false; 
   }
}


//-->
</script> 
</head>
<body>

<?php //require('header.inc') ?>
<?php require('menu.inc') ?>

<div style="position:absolute; top:5px; left:200px; width:550px">

<span class="head3">New Campus Form</span><br><br>
  
<form method="POST" action="add_campus_details_form.php" name="AddCampus" onSubmit="try{if (Validate(this)) this.submit();}catch(e){}return false;">

<span id="mySpan1" class="errmsg"><?php echo $Message_Campus?></span><br>
Campus Name: <br><input type="text" name="Campus" value="<?php echo $Campus?>"/><br><br><br>

<span id="mySpan2" class="errmsg"><?php echo $Message_CampusEmail?></span><br>   
Campus Email: <br><input type="text" size="45" name="CampusEmail" value="<?php echo $CampusEmail?>"/><br><br>
Confirm Email Address: <br><input type ="text" size="45" name="ConfirmEmail" value="<?php echo $ConfirmEmail?>"/><br><br>

<input type="submit" name="SubmitB" value="Submit"/>
</form>  
<br><br><br><br>

<a href="display_campus_details.php?Action=Edit">Back to Edit Campus Details List</a>
</div>

</body>
</html>
Reply With Quote
  #16 (permalink)  
Old Feb 12th, 2008, 13:03
spinal007's Avatar
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 22
Posts: 1,619
Blog Entries: 1
Thanks: 0
Thanked 2 Times in 2 Posts
Send a message via ICQ to spinal007 Send a message via MSN to spinal007 Send a message via Yahoo to spinal007 Send a message via Skype™ to spinal007
Re: Form validation help!

If you want to SEE the errors you have to remove the try{}catch{} block!!!
Only put try{}catch{} in AFTER you know it all works ok, otherwise you can't debug it!

And if you do need to use try{}catch{}, then USE ALERT OT TELL YOURSELF WHAT'S GOING ON, this this:
onsubmit="try{if (Validate(this)) this.submit();}catch(e){ alert(e); }; return false;"

Anyway,
ERROR 1: elseif not defined. VB uses "ElseIf", Javascript uses "else if".
You should have picked this up because of the highlighting. Try using an editor like Notepad++.

ERROR 2: the line Errors=Errors+ValidateValues(f) had a logic error.
The ValidateValues did not return a number, it returned true/false.
This caused the Validate() function to always return true, so the form was always submitted.

So, here's what you need:
On the form:
Code: Select all
onsubmit="try{if(Validate(this)) this.submit();}catch(e){ alert(e); }; return false;"
javascript:
Code: Select all
function Validate(f){
   return (ValidateValues(f)==0 ? true : false );
}

function ValidateValues(f){
   var Errors = 0
   if((document.AddCampus.Campus.value+'').length<1)
   {
      document.getElementById('mySpan1').innerHTML='Please Enter a Campus Name!';
      Errors++
   }
   if(document.AddCampus.CampusEmail.value =="")
   {
      Errors++
      document.getElementById('mySpan2').innerHTML='Please Enter an Email Address!';
   }
   else if(!document.AddCampus.CampusEmail.value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/))
   {
      Errors++
      document.getElementById('mySpan2').innerHTML='Please Enter a Valid Email Address!';
   }
   else if(document.AddCampus.CampusEmail.value !== document.AddCampus.ConfirmEmail.value)
   {
      Errors++
      document.getElementById('mySpan2').innerHTML='The Email Addresses do not match, please re-confirm them!';
   }
   return Errors;
}
You're welcome.
Last Blog Entry: Random String in Javascript (Apr 21st, 2008)
Reply With Quote
  #17 (permalink)  
Old Feb 12th, 2008, 16:40
Junior Member
Join Date: Feb 2008
Location: England
Age: 21
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Form validation help!

Thank you so much!! That did it, although I removed the stuff on the onsubmit function and just went back to onsubmit="return Validate(this);" as it didn't seem to work with what you gave me before.

Edit: Nevemind if you are reading this I got that done, thanks again!

Last edited by psycho wolvesbane; Feb 12th, 2008 at 21:47.
Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On