I have the following PHP code, which uses server-side validation, which works fine. It the user leaves the text field empty it stores an error in a session array which is outputted on the page where the $_GET variable came from. I also implemented a snippet of javascript code that just checks to see if the cell is empty and throws up alert box. The problem is that both the javascript code and php error validation are both running when I click submit. The PHP code should be a backup to the javascript code in case the user has javascript turned off. The client-side validation should be the default. Not sure if this change should be made in my PHP Code or Javascript Code.

PHP CODE:

session_start();
require_once("../Modules/Connection_Functions.php");
require_once("../Modules/Query_Functions.php");	
	
	if(isset($_POST['submit']))
	{
		//Store Errors in an array
		$errors = array();
		
		
		$id2 = $_POST['id'];
		$credential_cat = $_POST['credential_cat'];
		
		
		if(!isset($credential_cat) OR empty($credential_cat))
		{
			$errors[] = 'Enter Credential Category.';
		}
		
		if (count($errors) > 0) 
		{  
			$_SESSION["errors"] = $errors;  
			header("location: View_Credential_Categories.php");
		}
		else
		{

			queryUpdate_credCat();
		}
	}
	else if (isset($_GET['id']))
	{
	
			$id = $_GET['id'];
		
		foreach(queryFillForm_credCat() as $row)
		{
			$credential_cat = htmlspecialchars($row['credential_categoryName']);
		}
			
	}
	else
	header("Location: View_Credential_Categories.php");

HTML CODE:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return validate_form(this)">
<h2>Edit Credential Category</h2>
<table id="edit">
<table>
<tr>
<td><label>Credential Category:</label></td>

<td><input type="text" maxlength=40 name="credential_cat" size="40" value="<?php echo $credential_cat; ?>" /></label><br /></td>
</tr>
</table>
<input name="id" type="hidden" value="<?php echo $id; ?>" /><br/>
<input name="submit" type="submit" value="Edit" />

</form>

Javascript Code:

function validate_required(field,alerttxt)
{
with (field)
  {
  if (value==null||value=="")
    {
    alert(alerttxt);
	return false;
    }
  else
    {
    return true;
    }
  }
}


function validate_form(thisform)
{
with (thisform)
  {
  if (validate_required(credential_cat,"Credential Category must be filled out!")==false)
  	{
	  email.focus()
	  ;return false;
	}
	
	  
  }
}

Here's a hint: You want to use both. The PHP shouldn't be a "backup" since you can't trust client-side validation. Client-side validation is nice to give users some feedback but it can also be malicious.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.