Jump to content

Validate form data using PHP


VelvetMirror

Recommended Posts

If I have a form I can use javascript in order to validate the data. If all is correct I send the data and if something is wrong, I show an error message and the form isn't sent, something like this:

<script type="text/javascript" >	function validateForm() {		var number = form.number.value;		if(number == "") {			alert("You must write a number!");			return false;		}		else			return true;	}</script><form name="form" id="form" class="form" action="index.php" onsubmit="return validateForm(this)" method="post">	<label for="number">Number:</label>	<input type="text" name="number" id="number" />	<input type="submit" name="insert" id="insert" value="Send" class="submit" /></form>

I would like to know if it's possible to use PHP in order to do the data validation BEFORE any data is sent (as I can do with javascript). Something like this:

<?php// Here we would validate and sanitize the dataif(!filter_var($int, FILTER_VALIDATE_INT))  {	// Here we show an error message and the form data is not sent to 'index.php'  }else  {  // Here we have checked that the data is all right and send it to 'index.php'  }?>

The reason I would like to do this is because I like much better the filters that PHP has in order to perform a validation.

Link to comment
Share on other sites

Usually, you check if the data passes the validation, and if it does, then continue.

if (data is valid) {   //continue} else {   echo 'errors';}

If you need more specific errors than "something is wrong", you could check each field individually.

$max_val = 500;$errors = '';if ( !filter_var($_POST['number'], FILTER_VALIDATE_INT) ) {  $errors .= 'Please enter a valid number.';} if ( $_POST['number'] > $max_val ) {  $errors .= 'Please enter a number that is no greater than ' . $max_val;}if ( !$errors ) {  // continue}

Link to comment
Share on other sites

I would like to know if it's possible to use PHP in order to do the data validation BEFORE any data is sent (as I can do with javascript)
you cant validate using php in client browser. you can only do when it sent back to the server. it is the way js and php works. javascript can be used for validating data before sending it to server. and php validation is the last option before doing anything with external data. as fmdpa showed ...you can use it to validate using php but you can do only if it being submited to the server.using javascript to validate can reduce the server stress but its not reliable. so you may like to do the both. incase of js validation skiped php will surely do the rest of job.
Link to comment
Share on other sites

That makes sense. I thought may be you could call a PHP function from a JavaScript function in order to perform a PHP validation before the form is submited, but it seems it doesn't work that way. Although I still don't understand how PHP validation really works.Imagine you have a form and you only want to use PHP validation because javascript is disable or simply because you don't wanna use javascript.You type the data, send the form, perform the validation with PHP in the target url, and then the data is wrong. How would you show again the form if you already sent it?

Link to comment
Share on other sites

you can submit the form in itself the scirpt. you will check that form has been submited or not.by checking the condition using isset() if submited check the inputs.validate them.if all input is ok process the form else manupulate the errors an show themsomething like..

/<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'><input type='text' name='name' value='' /><input type='submit' name='go' value='go' /><?phpif(isset($_POST['go'])){ //validate the inputs eg. $_POST['name']//if ok process it//else show the errors}?>

Link to comment
Share on other sites

I think I finally get it, hopefully something like this:

<script type="text/javascript" >	function validateForm() {		var number = form.number.value;		if(number == "") {			alert("You must write a number!");			return false;		}		else			return true;	}</script><?phpif (isset($_POST['insert'])) {	$int = $_POST['number'];// Here we would validate and sanitize the data	if (!filter_var($int, FILTER_VALIDATE_INT)) {		echo "error!";?>		<form name="form" id="form" class="form" action="test.php" onsubmit="return validateForm(this)" method="post">			<label for="number">Number:</label>			<input type="text" name="number" id="number" />			<input type="submit" name="insert" id="insert" value="Send" class="submit" />		</form><?php	} else {		echo "all fine!";	}} else {?>	<form name="form" id="form" class="form" action="test.php" onsubmit="return validateForm(this)" method="post">		<label for="number">Number:</label>		<input type="text" name="number" id="number" />		<input type="submit" name="insert" id="insert" value="Send" class="submit" />	</form><?php}?>

Link to comment
Share on other sites

Truly, if you really needed to, you could have 3 PHP files (feel free to change filenames):good.phpbad.phpvalidate.phpYour form points to validate.php,Then you do something like this:

$var1 = $_POST["one"];$var2 = $_POST["two"]; (etc)then if ($var1 && $var2){header('Location: good.php');}else{header('Location: bad.php');}

then obviously you'd want to change good.php to the code you want, and bad.php to an error message.Although this IS a last resort, it'd work.

Link to comment
Share on other sites

Truly, if you really needed to, you could have 3 PHP files (feel free to change filenames):good.phpbad.phpvalidate.phpYour form points to validate.php,Then you do something like this:
$var1 = $_POST["one"];$var2 = $_POST["two"]; (etc)if ($var1 && $var2){header('Location: good.php');}else{header('Location: bad.php');}

then obviously you'd want to change good.php to the code you want, and bad.php to an error message.Although this IS a last resort, it'd work.

yeah, IMO that's just asking to for a maintenance nightmare. Usually forms are submitted to themselves, but if that's a little advanced for the OP at this point, I personally wouldn't encourage the use of 3 pages to the do the job of one. i.e.
$var1 = $_POST["one"];$var2 = $_POST["two"]; (etc)then if ($var1 && $var2){  echo 'successful submission';}else{  echo 'un-successful submission';};

Using that basic control structure, the OP can choose to have that one page output anyway he wants. He could just have a single div on the page to contain a message and have the div show text based on the success check of the submission. i.e.

<?php$var1 = $_POST["one"];$var2 = $_POST["two"]; (etc)if ($var1 && $var2){  $msg = 'Form submitted successfully, thank you for your time';}else{  $msg = 'I'm sorry, there was an error in your submission.  Please go back and try again';};?><html><body>  <div style="border: 3px dotted orange; width:500px; background-color:gray; margin: 0px auto">	<p style="color:#efefef;"><?php echo $msg ?></p>  </div></body><html>

Link to comment
Share on other sites

if you redirect the user so it will loose his get/post data.though if you try to propogate the data again to the redirected location in header likeheader("Location: good.php?var1=$var1");it will take you where have you been. as its sends the user data over the stream. you must to validate it again in good.php.so it will not be apropiate. good one is as thescintist told if you validate the data in validate.php and show the errors on that page if you needed. else do job absed on the submite data.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...