Jump to content

Form Validation


handley

Recommended Posts

Hi all!

 

Im trying to modify a script so that when a user submits data on a form if there are any errors it flags all errors and not just the first one the script comes to and 'dies'.

 

Heres the form code

 

<?php
session_start();
?>
<!--//-----------------------------------------------------------------------------------------------+             |
//  Sample AJAX web form By: Codex-m                                                                               |
//	http://www.php-developer.org                                                                                   |
//  You are free to use and improve this script provided you link to author web site: http://www.php-developer.org |
//-------------------------------------------------------------------------------------------------------------->
<html>
<head>
<title>Sample AJAX Web Form</title>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function sendRequest() {
new Ajax.Request("ajaxvalidate.php",
{
method: 'post',
parameters: 'name='+$F('name')+'&phonenumber='+$F('phonenumber')+'&age='+$F('age')+'&captcha='+$F('captcha'),
onComplete: showResponse
});
}
function showResponse(req){
$('show').innerHTML= req.responseText;
}
</script>
<style type="text/css">
P.yellow {background-color: #ffff00;}
</style>
</head>
<body>
<h3>This is a sample PHP web form with AJAX validation</h3>
Please complete the form below and then press "Submit button".<br />
<br /><br />
<form action="/ajaxwebform/ajaxvalidate.php" method="post" onsubmit="return false;">
Enter your Full Name, First name and Last name ONLY (Example: John Doe)<br />
<input style="background-color: #FFFFC0" type="text" name="name" id="name" size="50">
<br /><br />
Enter your Phone number (numbers only, no dashes and spaces)<br />
<input style="background-color: #FFFFC0" type="text" name="phonenumber" id="phonenumber" size="35">
<br /><br />
Enter your Age (Numbers only)<br />
<input style="background-color: #FFFFC0" type="text" name="age" id="age" size="50">
<br /><br />
<img src="/ajaxwebform/captcha.php" />
<br />
Enter the Captcha as shown above:
<br /> <br />
<input style="background-color: #FFFFC0" type="text" name="captcha" id="captcha" size="10">
<br /> <br />
<input type="submit" value="Submit" onClick="sendRequest()">
</form>
<br />
This form will validate your data entry using AJAX. If you are correct with your data entry, the entire information entered will be shown in this page without reloading.
<br />
<br /><br />
<p class="yellow" id="show"></p>
</body>
</html>

 

Heres the php validating code

 

<?php
session_start();
?>
<!--//-----------------------------------------------------------------------------------------------+             |
//  Sample AJAX web form By: Codex-m                                                                               |
//	http://www.php-developer.org                                                                                   |
//  You are free to use and improve this script provided you link to author web site: http://www.php-developer.org |
//-------------------------------------------------------------------------------------------------------------->
<?php
//start session to recover captcha answers
//connect to database
$username = "root";
$password = "";
$hostname = "localhost";
$database = "newdb";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
//extract form inputs
$name =$_POST['name'];
$phonenumber =$_POST['phonenumber'];
$age =$_POST['age'];
$usercaptchaanswer =$_POST['captcha'];
$correctcaptcha = $_SESSION['answer'];
//sanitize early for any possible MySQL entry
$name = mysql_real_escape_string(stripslashes(trim($name)));
$phonenumber = mysql_real_escape_string(stripslashes(trim($phonenumber)));
$age = mysql_real_escape_string(stripslashes(trim($age)));
$usercaptchaanswer = mysql_real_escape_string(stripslashes(trim($usercaptchaanswer)));
$correctcaptcha = mysql_real_escape_string(stripslashes(trim($correctcaptcha)));
Validate captcha entry
if ($correctcaptcha != $usercaptchaanswer) {
echo 'ERROR: You have entered wrong captcha code';
die ();
}
//Step 2 of data validation: check for blank entries
if (empty($name)) {
//name field is blank
echo 'ERROR: The name field is empty.';
die ();
}
if (empty($phonenumber)) {
//phone field is blank
echo 'ERROR: The phone field is empty.';
die ();
}
if (empty($age)) {
//age field is blank
echo 'ERROR: The age field is empty.';
die ();
}
if (empty($usercaptchaanswer)) {
captcha field is blank
echo 'ERROR: The captcha field is empty.';
die ();
}
//Step 3 of data validation: Ensuring correct format
//Step 3.1 validate full name, presence of first name and last name
$mystring = $name;
$findme   = ' ';
$pos = strpos($mystring, $findme);
$actualposition =$pos + 1;
//count strings
$count =strlen($mystring);
//count the number of characters for the first name
$countfirstname = $actualposition - 1;
//count the number of characters for the last name
$countlastname = $count - $actualposition;
//detect if full name has middle name
$posmid= strpos($mystring,$findme,$actualposition) + 1;
$middleadjust = $posmid - $actualposition;
$purealpha = str_replace(" ", "x", $mystring);
if ($actualposition==1) {
echo 'ERROR: You either forgot your first name or your last name.';
die ();
}
if ($countfirstname <2) {
echo 'ERROR: You are using an invalid first name, it should contain more than one character.';
die ();
}
if ($countlastname <2) {
echo 'ERROR: You are using an invalid last name, it should contain more than one character.';
die ();
}
if ($middleadjust >= 2) {
echo 'ERROR: You should not be using a middle name, please use only first name and last name.';
die ();
}
if (!(ctype_alpha($purealpha))) {
echo 'ERROR: Full name can only consist of alphabetic characters.';
die ();
}
//Step 3.2 Validate phone number
if (!(ctype_digit($phonenumber))) {
echo 'ERROR: A phone number should consist of numerical digits only and no spaces between numbers';
die ();
}
//Step 3.3 Validate age
if (!(ctype_digit($age))) {
echo 'ERROR: Your age should consist of numerical digits only and no spaces between numbers';
die ();
}
//Step 4. If all data entry is correct, show results in another page, assigned all values to sessions
echo 'Thank you for the correct data entry, below are the information entered:';
echo '<br />';
echo 'Your full name is: '.$name;
echo '<br />';
echo 'Your phone number is: '.$phonenumber;
echo '<br />';
echo 'Your age is: '.$age;
echo '<br />';
echo '<a href="/ajaxwebform/ajaxwebformtest.php">Click here to enter another data.</a>';
$_SESSION = array ();
session_destroy ();
mysql_close($dbhandle);
?>

Link to comment
Share on other sites

Im trying to modify the script so that when there is an validation error it flags that error but instead of stopping on the 'die' and just showing the one error it runs the whole script and then posts all errors to the user.

 

I guess i'm looking for a replacement for the 'die'?

 

Sorry for not making it clear! been a long day! :P

Link to comment
Share on other sites

Hi,

 

Not tested but try this:

 

<?php
session_start();
?>
<!--//-----------------------------------------------------------------------------------------------+             |
//  Sample AJAX web form By: Codex-m                                                                               |
//



http://www.php-developer.org                                                                                   |
//  You are free to use and improve this script provided you link to author web site: http://www.php-developer.org |
//-------------------------------------------------------------------------------------------------------------->
<?php
//start session to recover captcha answers
//connect to database
$username = "root";
$password = "";
$hostname = "localhost";
$database = "newdb";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");

// Fetch form data and cleanse
$name = mysql_real_escape_string(stripslashes(trim($_POST['name'])));
$phonenumber = mysql_real_escape_string(stripslashes(trim($_POST['phonenumber'])));
$age = mysql_real_escape_string(stripslashes(trim($_POST['age'])));
$usercaptchaanswer = mysql_real_escape_string(stripslashes(trim($_POST['captcha'])));
$correctcaptcha = mysql_real_escape_string(stripslashes(trim($_SESSION['answer'])));

// Validate captcha entry
if ($correctcaptcha != $usercaptchaanswer) {
$error .= 'ERROR: You have entered wrong captcha code';
}
//Step 2 of data validation: check for blank entries
if (empty($name)) {
//name field is blank
$error .= 'ERROR: The name field is empty.';
}
if (empty($phonenumber)) {
//phone field is blank
$error .= 'ERROR: The phone field is empty.';
}
if (empty($age)) {
//age field is blank
$error .= 'ERROR: The age field is empty.';
}
if (empty($usercaptchaanswer)) {
// captcha field is blank
$error .= 'ERROR: The captcha field is empty.';
}
//Step 3 of data validation: Ensuring correct format
//Step 3.1 validate full name, presence of first name and last name
$mystring = $name;
$findme   = ' ';
$pos = strpos($mystring, $findme);
$actualposition =$pos + 1;
//count strings
$count =strlen($mystring);
//count the number of characters for the first name
$countfirstname = $actualposition - 1;
//count the number of characters for the last name
$countlastname = $count - $actualposition;
//detect if full name has middle name
$posmid= strpos($mystring,$findme,$actualposition) + 1;
$middleadjust = $posmid - $actualposition;
$purealpha = str_replace(" ", "x", $mystring);
if ($actualposition==1) {
$error .= 'ERROR: You either forgot your first name or your last name.';
}
if ($countfirstname <2) {
$error .= 'ERROR: You are using an invalid first name, it should contain more than one character.';
}
if ($countlastname <2) {
$error .= 'ERROR: You are using an invalid last name, it should contain more than one character.';
}
if ($middleadjust >= 2) {
$error .= 'ERROR: You should not be using a middle name, please use only first name and last name.';
}
if (!(ctype_alpha($purealpha))) {
$error .= 'ERROR: Full name can only consist of alphabetic characters.';
}
//Step 3.2 Validate phone number
if (!(ctype_digit($phonenumber))) {
$error .= 'ERROR: A phone number should consist of numerical digits only and no spaces between numbers';
}
//Step 3.3 Validate age
if (!(ctype_digit($age))) {
$error .= 'ERROR: Your age should consist of numerical digits only and no spaces between numbers';
}

// check if errors exist
if(isset($error)) {
echo $error . '<br />';
} else { // else no errors found continue
//Step 4. If all data entry is correct, show results in another page, assigned all values to sessions
echo 'Thank you for the correct data entry, below are the information entered:';
echo '<br />';
echo 'Your full name is: '.$name;
echo '<br />';
echo 'Your phone number is: '.$phonenumber;
echo '<br />';
echo 'Your age is: '.$age;
echo '<br />';
echo '<a href="/ajaxwebform/ajaxwebformtest.php">Click here to enter another data.</a>';
$_SESSION = array ();
session_destroy ();
mysql_close($dbhandle);
}
?>

 

Also captcha field is blank was not commented out plus Validate captcha entry was not commented out which would have returned php errors. But has been corrected in the edited code i posted above.

 

Also there is no need to have:

 

<?php
//extract form inputs
$name =$_POST['name'];
$phonenumber =$_POST['phonenumber'];
$age =$_POST['age'];
$usercaptchaanswer =$_POST['captcha'];
$correctcaptcha = $_SESSION['answer'];
//sanitize early for any possible MySQL entry
$name = mysql_real_escape_string(stripslashes(trim($name)));
$phonenumber = mysql_real_escape_string(stripslashes(trim($phonenumber)));
$age = mysql_real_escape_string(stripslashes(trim($age)));
$usercaptchaanswer = mysql_real_escape_string(stripslashes(trim($usercaptchaanswer)));
$correctcaptcha = mysql_real_escape_string(stripslashes(trim($correctcaptcha)));
?>

 

First it has fetched form data them repeated the code to the cleanse it, all that can be done together. I edited this again as it's no point in having more code than what is needed.

Link to comment
Share on other sites

Cheers for the help!

 

Yeah I uncommented the captcha parts while I posted this thread, cheers for commenting them out!

 

Will test this in the morning!

 

Thanks again! :)

 

Hi,

 

I just updated my post above. You may have noticed. Either way glad to be of help. I have been programming for about 18 months on and off but i find it's the most simple things sometimes that can be the most confusing. Although i have learnt tons i still get stuck or don't understand little silly things lol.

 

 

Link to comment
Share on other sites

Hi,

 

ive tested the code that you modified now and it works great!

 

thanks alot for the help it is much appreciated! I have only just started with php but been coding html for ages so I can understand what the code is doing but I haven't fully figured out how to modify certain things!

 

Thanks again!

Link to comment
Share on other sites

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.