Page 1 of 1

Form Validation (PHP vs. Javascript) ??

Posted: Fri Aug 13, 2010 7:59 pm
by diseman
Hello Experts,

Today I've been learning how to do form validation. When I finally got it to work in PHP, I see that after clicking the submit button all my data disappears. So even though I got my form validation errors, I would have to start all over and redo the form. That's not good. Right now I have form action="", so it's not even going anywhere.

So the question is, can you do PHP form validation without losing all the entries? Can my entries remain on the page while error messages appear that allow me to fix the missing entries and then submit again without having to start over?

OK, so I found some sites talking about using Javascript to do this exact thing. However, the JS code I saw has a pop-up window appear that I don't like. I would rather my error messages be on the page itself. However, if using Javascript is the accepted norm for form validation that's fine. I just need someone to tell me if that's true since I don't really know what the standard is.

OK. Looking forward to any replies.

Thank you....

Re: Form Validation (PHP vs. Javascript) ??

Posted: Sat Aug 14, 2010 12:14 am
by arrielmabale
Yes these input elements looses their contents.
What you should do is fill it up again using php
ex.

Code: Select all


$name = $_GET['name'];

<form method="get">
<input name="name" value="<?=$name?>" />
</form>

Note that you filled the field again with $name ^_^
God speed

Re: Form Validation (PHP vs. Javascript) ??

Posted: Sat Aug 14, 2010 1:51 am
by raj86
you can also validate your form this way

on top of your page you declare .error in style tag
<style>
.error{
color:#F00;
}

/* Displays Star in Red color */
.default_star{
color: red;
font-weight: bold;
}
</style>


than you can use the following php code

Code: Select all

<?php
$error=0;
$done='';
if( isset($_POST['submit']))
{
$bsr=($_POST['bsr']);
	if(preg_match('/[^0-9]/', $bsr))
    {
		echo ("Error: BSRN should be a numeric value.<br/>");
		$error=1;
	}	
	$emptyp=($_POST['emptyp']);

	if ($error==0 && $done==false && isset($_POST['emptyp']) && ($_POST['emptyp'] == 'Select'))
	{
    	echo("Please select employee type.<br/>");
		$error=1;
   	} 
	$name=($_POST['name']);
	
	if($error==0 && trim($_POST['name']) == "")
    {
		echo('<font color="##FF0000">Please enter a valid name.</font><br/>');
		$error=1;
	}
	else if(preg_match('/[^A-Za-z .]/', $_POST['name']))
	{
		echo ("Error: Name should be a character value.<br/>");
		$error=1;
	}		 
if($error==0)
	{
		$query = "INSERT INTO `paymajor` (`PSRN`, `BSRN`, `FLAG`, `EMP_TYPE`, `NAME`) VALUES ('$psrn', '$bsr', '$flg', '$emptyp', '$name')";

		$result = mysql_query($query)  or die ("Error in query: $query<br/>");
		if($result)
		{
			echo "data entered succesfully";
			$done=true;
			$psrn++;
			
		}	
	}
and also use the following html code in your form
<form action="" id="form2" method="post" name="form1" class="style1">
<td width="50%" valign="top">
<font color="##FF0000" >*</font>
<label>indicates mandatory field</label>
<table border="0" width="100%" cellpadding="10">
<tr>
<td width="50%" colspan="2" valign="top" >
<?php
echo "1. PSRN: ",$psrn;
?>
<br><br>
<label>2. BSRN</label>
<input type="text" name="bsr" size="3" maxlength="3" onKeyUp="checkNumber(this.value)" onclick='highlight(this);' value="<?php if (isset($_POST['submit'])) echo $_POST['bsr'];?>">

<br><br>
<label>3. Employee Type</label>
<font color="##FF0000" >*</font>
<select name="emptyp">
<option value="2" <?php if ($done==false && isset($_POST['emptyp']) && $_POST['emptyp'] == '2') { echo "selected='selected'"; }?> >2 (Teaching faculty)</option>
<option value="3" <?php if ($done==false && isset($_POST['emptyp']) && $_POST['emptyp'] == '3') { echo "selected='selected'"; }?> >3 (Supporting staff)</option>
<option value="4" <?php if ($done==false && isset($_POST['emptyp']) && $_POST['emptyp'] == '4') { echo "selected='selected'"; }?> >4 (Helping staff)</option>
</select> <br> <br>

<label>4. Name</label>
<font color="##FF0000" >*</font>
<input type="text" name="name" size="30" maxlength="30" onKeyUp="checkName(this.value)" value="<?php if ($done==false && isset($_POST['submit'])) echo $_POST['name']; ?>"><br><br>


hope this will help you to some extent.........

Re: Form Validation (PHP vs. Javascript) ??

Posted: Sat Aug 14, 2010 6:08 am
by oscardog
raj86 your script is a little messy and not particularly optimised. Even if the first validation returns an error you still do multiple IF checks later on, it would be much better to have a function called (for example) validateInput and when the form is submitted call that function.

An example is below (not all validation is included, just enough to show what I mean).

Code: Select all

<?php

function validateInput() {

$bsr=($_POST['bsr']);
        if(preg_match('/[^0-9]/', $bsr))
    {
        return "Error: BSRN should be a numeric value.";
    }    
    
    if($error==0 && trim($_POST['name']) == "")
    {
        return "Please enter a valid name.";
    }  
    
return "validated";
}

if(isset($_POST['submit'])) {
$isError = validateInput();
if($isError=="validated")
        {
                $query = "INSERT INTO `paymajor` (`PSRN`, `BSRN`, `FLAG`, `EMP_TYPE`, `NAME`) VALUES ('$psrn', '$bsr', '$flg', '$emptyp', '$name')";

                $result = mysql_query($query)  or die ("Error in query: $query<br/>");
                if($result)
                {
                        echo "data entered succesfully";
                        $done=true;
                        $psrn++;  
                }      
        }
}
This is much more efficient. This way you execute the minimum amount of conditional statements possible. If you wanted an external function (as in have a functions.php file so you can use them in more than one place) you could pass the POST array to the function.

Of course you would also need to add to my code the form and the part where the error message is displayed if there is one.

Re: Form Validation (PHP vs. Javascript) ??

Posted: Sat Aug 14, 2010 12:12 pm
by califdon
To try to answer the original question, it's recommended that you always validate BOTH in Javascript (for user convenience, assuming JS has not been disabled in the browser) AND when it is processed in the server (PHP) upon submission and before writing to the database or even issuing a query based on user input. This is very important for security reasons.

Re: Form Validation (PHP vs. Javascript) ??

Posted: Sat Aug 14, 2010 12:16 pm
by diseman
Thank you all.

I was pretty sure what I was looking for could be done in PHP and arrielmabale gave me the start I needed to get it working like I wanted. Thank you arrielmabale and everyone else that commented.