Jump to content

My validation scripts are not outputting the errors to my form page, i have added the scripts of the validation page and the form page


Recommended Posts

Firstly, dont post pictures of code. Post the actual code using the code formatting button <>

  1. Depending on the name of a button to be submitted for your script to work will completely fail in certain cases. You need to check the POST REQUEST.
  2. Do not create variables for nothing
  3. Trim the POST array, THEN check for empty
  4. Errors messages should be arrays.
  5. You must kill the script after header redirect
  6. Do not output user supplied data to the page. Use htmlspecialchars
  7. Get rid of most if not all those elses
  8. Your code is vulnerable to an XSS attack. See #6
  9. Posting again for "urgent" help is not going to get you help any faster.

 

Edited by benanamen

1. What do you mean i should check the post method request?

2. trim the post array?

3. kill the script after header redirect?

 

 

 

 

//This is the php code

 

<?php

 session_start();
	
	if(isset($_POST['next']))
	{
		
		$firstn=$_POST['firstname'];
		$lastn=$_POST['lastname'];
		$dateofbirth= $_POST['dateofbirth'];
		$title=$_POST['title'];
		$TRN= $_POST['trn'];
		$firstnameerror="";
		$lastnameerror="";
		$trnerror=null;
		$doberror="";
		$titleerror="";
		
		$_SESSION['errorflag'] = 0;
		
		
		
		
		if(empty($_POST['firstname']))
		{
			$firstnameerror= "<p style= 'color:red'> First name is required </p>";
			header("Location: addpatientform.php");
		}
		
			else
			{
				$firstn=$_POST['firstname'];
			}
			
		
		if(empty($_POST['lastname']))
		{
			$lastnameerror= "<p style= 'color:red'> Last name is required </p>";
			header("Location: addpatientform.php");
		}
		
		else
		{
			$lastn= $_POST['lastname'];
		}
		
		if(preg_match("([a-zA-Z'])",$firstn))
		{
			echo 'valid first name given';
		}
		else
		{
			$firstnameerror= "invalid first name given";
		
		}
		
		if(preg_match("([a-zA-Z'])",$lastn))
		{
			echo 'valid last name given';
		}
		
		else
		{
			$lastnamerror= "invalid last name";
			header("Location: addpatientform.php");
			
		}
		
		
		if(empty($_POST['dateofbirth']))
		{
			$doberror= "<p style= 'color:red'> Date of birth is required please enter date of birth </p>";
			header("Location: addpatientform.php");
			
		}
		else
		{
			$dateofbirth=$_POST['dateofbirth'];
		}
		
		if(empty($_POST['trn']))
		{
			$trnerror= "<p style= 'color:red'> TRN IS REQUIRED </p>";
			header("Location: addpatientform.php");
			
		}
		else
		{
			$TRN=$_POST['trn'];
		}
		
		if(!filter_var($TRN, FILTER_VALIDATE_INT))
		{
			$trnerror= "<p style= 'color:red> Incorrect TRN format </p>";
			header("Location: addpatientform.php");
			
		}
		
	if(strlen($TRN) > 9 || strlen($TRN) < 9)
		{
			$trnerror= "<p style= 'color:red> <TRN LENGTH IS NOT 10 DIGITS </p>";
			header("Location: addpatientform.php");
			
		}
			
	
	

	}






?>

 

This is the form code

<?php

session_start();

$firstn="";
$lastn="";
$dateofbirth= "";
$title="";
$TRN= "";
$firstnameerror="";
$lastnameerror="";
$trnerror=null;
$doberror="";
$titleerror="";

?>




<!DOCTYPE html>
	<html>
		<head>
			<title> Medical Login Page </title>
			<link rel="stylesheet" type="text/css" href="Registrationcss.css">
		</head>

	
<body background="testtube.jpg">
	
 <div id="login.wrapper">
		<div class="container">
		
		</div>
		
	<form action="validateregistrationpage.php" method="POST" id="login">
		<center><h2>MEDICAL PATIENT REGISTRATION FORM</h2></center>
		<label> Title </label>
		<select name= "title" placeholder= "--------" value= " <?php echo $title;?>">
			<option  value="mr" value=""> Mr. </option>
			<option value= "mrs" value = "" > Mrs. </option>
			<option value= "sir" value= " "> Sir. </option>
			<option value= "miss" value= " "> Miss. </option>
		</select><br><br>
		
		<label> First Name </label>
		<input type= "text" name="firstname" placeholder="Enter patient's first name" value="<?php echo $firstn; ?>"/> 
		<?php if(isset($firstnameerror)) { ?>
			<?php echo $firstnameerror ?>
		<?php } ?>
		
		<label> Last Name </label>
		<input type= "text" name="lastname" placeholder="Enter patient's last name" value="<?php echo $lastn; ?>"> 
		
		<label> Date of Birth </label>
		<input type= "date" name="dateofbirth" placeholder="select patient's date of birth" value= "<?php echo $dateofbirth; ?>" >
		
		<label> TRN </label>
		<input type= "text" name="trn" placeholder="Enter patient's 9 digit TRN" value= "<?php echo $TRN; ?>" >  <br><br>
		
		<button  type="submit" name="next" id="submit"> Next</button>
		


	</form>
	
	</div>
</body>
</html>

 

2 minutes ago, Aldayne_Henry said:

1. What do you mean i should check the post method request?

2. trim the post array?

3. kill the script after header redirect?

1.

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//Process form
}

2. https://www.php.net/manual/en/function.trim.php

3. https://www.php.net/manual/en/function.exit.php

Your primary problem is that variables created in page 2 are no longer available when you go back to page 1. You need to send the values to the page and the values need to urlencode()d.

Also, put your errors in an array so you notify the user of all errors once instead of continually going to and fro betwen the pages.

Happily there is an http_build_query() function that is of great help here.

Example

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {                                     // was data sent from the form?
    $post = array_map('trim', $_POST);                                          // remove unwanted whitespace
    
    $errors = [];
    
    if ($post['field1'] == '') {
        $errors[] = '"field1" must have a value';
    }
    if ($post['field2'] == '') {
        $errors[] = '"field2" must have a value';
    }
    if ($post['field3'] == '') {
        $errors[] = '"field3" must have a value';
    }
    
    if ($errors) {                                                              // if there were errors, return to the form to inform user
        $post['errors'] = $errors;                                              // also send the form values back so user doesn't have re-enter all data (sticky form)
        $qstr = http_build_query($post);
        header("Location: myform.html?$qstr");                                  // redirect to form with data and error messages
        exit;                                                                   // prevent further processing of this page
    }
    
    //
    // No errors 
    // so we can 
    // process the 
    // data here
    //
    
    header("Location: myform.html");                                            // return to a new form
}

?>

edit: PS Alternatively, do the POST processing at the top of the same page as the form.

Edited by Barand
<?php

 session_start();
	
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	$post= array_map('trim', $_POST);
	
	$errors = [];
	
	if ($post['firstname']== '')
	{
		$errors[] = "<p>Please enter the patient first name</p>" ;
		
	}
	
	if($post['lastname'] == '')
	{
		$errors[]=  "<p>Please enter a last name</p>" ;
		
	}
	
	if($post['dateofbirth'] == '')
	{
		
		$errors[]= "<p>Please select a date of birth</p>" ;
		
		
	}
	
	if($post['trn'] == '')
	{
		$errors[] = "<p>Please Enter a trn</p>" ;
		
	}
	
	if($errors)
	{
		$post['errors']= $errors;
		$qstr= http_build_query($post);
		header("Location:addpatientform.php?$qstr");
		exit;
		
	}
	
			header("Location:addpatientform2.php");
}






?>

so i tried it your way @Barand but the errors do not show in the form itself it shows in the url bar.. i want the errors to show up in the form

You have to display them on the form. What I showed was the method of getting them back to the first page.

For example

if (isset($_GET['errors']) && !empty($_GET['srrors']) )  {
    echo "<div style='padding:16px; background-color: red; color: white'>" . join('<br>', $_GET['errors']) . "</div>\n";
}

 

The first code I gave you goes in the validation page. The second piece of code goes in the form page.

image.thumb.png.46abd6e821046e13ad20315d79578bce.png

i have one more issue @Barand, how would i then output the data from the first page and the second page? i would want them to be displayed together on another page. is that possible?

 

@Barand sorry for being so bothersome.. i just need help with displaying the data from the seperate pages on one page.. is that possible? if so how do i go about it

 

<?php
session_start();




?>




<!DOCTYPE html>
	<html>
		<head>
			<title> Medical Login Page </title>
			<link rel="stylesheet" type="text/css" href="Registrationcss2.css">
		</head>

	
<body background="testtube.jpg">
		<?php
	if (isset($_GET['errors']) && !empty($_GET['errors']) )  
			{
    echo "<div style='padding:16px; background-color: red; color: white'>".join('<br>', $_GET['errors'])."</div>";
}
?>
 <div id="login.wrapper">
		<div class="container"> 
		</div>
		
	<form action="validateregistrationpage2.php" method="POST" id="login">
		<center><h2>MEDICAL PATIENT REGISTRATION FORM</h2></center>
		
		
		<label> Street Address </label>
		<input type= "text" name="address" placeholder="Enter patient's street address"/> 
		
		<label> District </label>
		<input type= "text" name="district" placeholder="Enter patient's District" > 
		
		<label> Parish/City </label>
		<input type= "text" name="parish" placeholder="Enter patient's parish"  >
		
		<label> Country </label>
		<input type= "text" name="country" placeholder="Enter patient's country of origin"  >  
		
		<label> Email </label>
		<input type= "text" name= "email" placeholder="Enter patient email address in form of (alexbrown@gmail.com)">
		
		<label> Telephone number </label>
		<input type= "text" name= "tele" placeholder="Enter patient telephone number in form of (555-555-555)">
		
		<button  type="submit" name="submitform" id="submit"> Submit Form</button>
		


	</form>
	
	</div>
</body>
</html>

i have another issue, the join function is now misbehaving.. it now gives me an error saying invalid arguements yet i did this for my other page and it worked perfectly. what is going on?

You have already passed information from page 1 to page 2. You have also passed information from page 2 to page 1. Why is a third page going to be different?

As my psychic powers have diminished with age, I have no idea what information you wish to send to yet another page, or why.

3 minutes ago, Aldayne_Henry said:

it now gives me an error saying invalid arguements

Are you sure that $_GET['errors'] is an array on this page?

1 minute ago, Aldayne_Henry said:

i want to display what the user has entered into the 2 form pages 

Why does that need yet another page?

All that you are doing could be easily accomplished with a single page, not three.

yes cause on my validation page i did $post['errors']= $errors and then on my form page i did  if(isset($_GET['errors']) && !empty($_GET['errors']))

 

so i dont know why it is not working for this page because it worked for the other

<?php

 session_start();
	
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	$post2= array_map('trim', $_POST);
	
	$verrors = [];
	
	if($post2['address'] == '')
	{
		$verrors= ' " Please enter a street address" ';
	}
	
	if($post2['district'] == '')
	{
		$verrors= ' "Please enter a district" ';
	}
	
	if($post2['parish'] == '')
	{
		$verrors= ' "Please enter a city or parish" ';
	}
	
	if($post2['country'] == '')
	{
		$verrors= ' "Please enter a country" ';
	}
	
	if($post2['email'] == '')
	{
		$verrors= ' "Please enter an email" ';
	}
	
	if($post2['tele'] == '')
	{
		$verrors= ' "Please enter a telephone number" ';
	}
	
	if(!empty($post2['address']))
	{
		if(!preg_match("/^[a-z0-9- ]+$/i", $post2['address']))
		{
			$verrors= ' "Enter a valid address number" ';
		}
		
	}
		if(!empty($post2['district']))
		{
			if(!preg_match("([a-zA-Z' ])",$post2['district']))
			{
				$verrors= ' "Invalid district" ';
			}
		}
		
		if(!empty($post2['parish']))
		{
		if(!preg_match("([a-zA-Z' ])",$post2['parish']))
			{
			$verrors= ' "Invalid parish" ';
			}
		}
		
		if(!empty($post2['country']))
		{
		if(!preg_match(" ([a-zA-Z' ])", $post2['country']))
		{
			$verrors= ' "Invalid country" ';
		}
		}
		
		
	
		if(!empty($post2['email']))
		{
	if(!fliter_var($post2['email'], FILTER_VALIDATE_EMAIL))
	{
		$verrors= ' "This is an invalid email address" ';
	}
		}
		
		if(!empty($post2['tele']))
		{
			if(!is_numeric($post2['tele']))
			{
				$verrors= ' "You entered a invalid phone number with text or characters please do not enter" ';
	
			}
		}
		if(!empty($post2['tele']))
		{
			if(strlen($post2['tele']) > 7)
			{
				$verrors= ' "You entered a telephone number greater than 7 digits" ';
			}
			else if(strlen($post2['tele']) < 7)
			{
				$verrors= ' "You entered a phone number less than 7 digits" ';
			}
		}
		
		if($verrors)
	{
		$post2['verrors']= $verrors;
		$qstr2= http_build_query($post2);
		header("Location:addpatientform2.php?$qstr2");
		exit;
	}
	
		header("Location:welcome.php");	
}





?>
	

does the problem with the join have anything to do with my validation page? @Barand because i am looking all over and im not finding the error that may be causing this predicament

Your $verrors is a string variable, not an array. I did tell you to check that!

22 minutes ago, Aldayne_Henry said:

$verrors= ' "You entered a phone number less than 7 digits" ';

Mine is an array...

$errors[] = '"field1" must have a value';
       ^^

See the difference?

You first defined it as an empty array but then overwrote it by assigning string variables to it instead of appending to the array (as I did)

Edited by Barand

i have another issue.. @Barand i want to retain the post form data in the form fields so when there is an error it still keeps the data the user entered in the field.. is there anyway you can assist with that?

2 hours ago, Aldayne_Henry said:

i want to retain the post form data in the form fields so when there is an error it still keeps the data the user entered in the field.. is there anyway you can assist with that?

I already have. The $qstr that my above code sends back to the form (with the error messages) also contains the original form's data. You populate the fields values from that data in the $_GET array.

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.