if statement's not working - php

Forgive my noobness coding as I teach myself PHP (lol)!
The code below works almost perfectly for a form I want to create. Whenever the user hits the submit button, provided the form is all filled in correctly, the text "E-mail Sent Successfully" message appears at the top of the page. If any of the mandatory fields are incomplete or invalid, then an error message is returned underneath the corresponding input field and the "e-mail sent successfully" message does not appear. This works properly for all but the last if statement (antispam). Essentially, if you enter the correct answer (3) into the antispam box, then regardless of the other fields being filled in or not, the "e-mail Sent Successfully" message appears (it shouldn't do this as other fields are not filled out correctly). The "e-mail Sent Successfully" message should only appear if all the mandatory fields are completed correctly.
Whatever 'if statement' goes at the bottom adhere's to the same rule (i.e. if name was at the bottom of the if statements, then only name would need to be entered correctly for the e-mail sent successfully message to appear). It feels as though if the last if statement is passed as true, the other statements don't work.
<?php
if (isset($_POST['submit'])) {
$yourname = $_POST['yourname'];
$organisation = $_POST['organisation'];
$email_from = $_POST['email'];
$comments = $_POST['comments'];
$antispam = $_POST['antispam'];
$namestring = "/^[A-Za-z .'-]+$/";
$emailstring = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
$error_message_email = "";
$error_message_name = "";
$error_message_message = "";
$error_message_antispam = "";
if(!preg_match($namestring,$yourname)) {
$error_message_name .= "Please enter a valid name";
}
if(!preg_match($emailstring,$email_from)) {
$error_message_email .= "Please enter a valid e-mail address";
}
if(strlen($comments) < 4) {
$error_message_message .= "Please enter a valid message";
}
if($antispam != "3") {
$error_message_antispam .= "Please enter a valid answer";
}
else {
echo "E-mail Sent Successfully";
}
}
else {
$yourname="";
$organisation="";
$email_from="";
$comments="";
$antispam="";
$error_message_email = "";
$error_message_name = "";
$error_message_message = "";
$error_message_antispam = "";
}
?>
<form name="htmlform" method="post" action="ifandelse.php">
<table width="650px">
<tr>
<td>
<label for="yourname"><font color="#ff0000">*</font>Name:</label>
</td>
<td>
<input type="text" name="yourname" value="<?PHP echo$yourname;?>" maxlength="50" size="40"><br>
<div class="warning">
<?php print $error_message_name;?>
</div>
</td>
</tr>
<tr>
<td>
<label for="organisation">Organisation:</label>
</td>
<td>
<input type="text" name="organisation" value="<?PHP echo$organisation;?>"maxlength="50" size="40">
</td>
</tr>
<tr>
<td>
<label for="email"><font color="#ff0000">*</font>E-mail Address:</label>
</td>
<td>
<input type="text" name="email" value="<?PHP echo$email_from;?>" maxlength="80" size="40"><br>
<div class="warning">
<?php print $error_message_email;?>
</div>
</td>
</tr>
<tr>
<td valign="top">
<label for="comments"><font color="#ff0000">*</font>Message:<br></label>
</td>
<td>
<textarea name="comments" rows="8" cols="60"><?PHP echo$comments;?></textarea><br>
<div class="warning">
<?php print $error_message_message;?>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<font color="#ff0000">*</font>To avoid unwanted spam, please answer the following question correctly: 2 + 1 = <input type="text" name="antispam" value="<?PHP echo$antispam?>" maxlength="100" style="width:30px"><br>
<div class="warning">
<?php print $error_message_antispam;?>
</div>
</td>
</tr>
<tr>
<td>
</td>
<td style="text-align:center;">
<input type="submit" class="formsubmit" name="submit" value="Submit Form">
</td>
</tr>
</table>
</form>
Be most grateful for any help, I've had several friends look into this and we still can't figure out why it's doing this. Have tried nesting the 'if statements' differently, changing the if statement's to else if, etc with no joy :(
I've looked on the forums and can't find a solution that works for me.

You should use a variable to know if there was an error (or more than one) at the end of your verifications. Some code below to give you the general idea :
$isError = false;
if (!preg_match($namestring, $yourname)) {
$error_message_name .= "Please enter a valid name";
$isError = true;
}
if (!preg_match($emailstring, $email_from)) {
$error_message_email .= "Please enter a valid e-mail address";
$isError = true;
}
if (strlen($comments) < 4) {
$error_message_message .= "Please enter a valid message";
$isError = true;
}
if ($antispam != "3") {
$error_message_antispam .= "Please enter a valid answer";
$isError = true;
}
if ($isError) {
//do wathever you have to do
} else {
//send mail
echo "E-mail Sent Successfully";
}

The else statement is attached to you last if and only to this one. Hence, only the last condition matters regarding whether your success message is displayed or not. You'll have to chain your checks :
if (!preg_match($namestring, $yourname)) {
$error_message_name .= "Please enter a valid name";
}
elseif (!preg_match($emailstring, $email_from)) {
$error_message_email .= "Please enter a valid e-mail address";
}
elseif (strlen($comments) < 4) {
$error_message_message .= "Please enter a valid message";
}
elseif ($antispam != "3") {
$error_message_antispam .= "Please enter a valid answer";
} else {
echo "E-mail Sent Successfully";
}
Of course, this will still leave you displaying only one error message at a time, which is far from optimized but that's another matter.

Related

Redirecting page to a Success page if server validation is positive

I have a form with an action that is linked to the same PHP page contact.php. I have all the server side validation inside the form and it's all fine. It redirects the user to the same page with error messages echoed if needed while making the form STICKY (that is the main point of using the same page for errors).
What I would like is for there to be a success page redirect if the form was okay. I've read other posts on how to implement this, but I don't quite understand how to implement it in my code.
<?php
$fullname = $email = $reason = $contactbox = '';
$fullnameerr = $emailerr = $reasonerr = $contactboxerr = '';
if(data_post('submit')){
if(empty(data_post('firstname'))){
$fullnameerr = "Please enter a valid name";
}
else {
$fullname = clean_data(data_post('firstname'));
if (!preg_match("/^[a-zA-Z '']*$/", $fullname)){
$fullnameerr = "Please enter only alphabetical characters and white spaces";
}
}
if(empty(data_post('email'))){
$emailerr = "Please enter a valid e-mail";
}
else {
$email = clean_data(data_post('email'));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailerr = "Please enter a correct e-mail format (ex 'joe#cornell.edu')";
}
}
if(empty(data_post('reason'))){
$reasonerr = "Please select a reason for contact";
}
else{
$reason = clean_data(data_post('reason'));
}
if(empty(data_post('contacttext'))){
$contactboxerr = "Please elaborate on your reason";
}
else{
$contactbox = clean_data(data_post('contacttext'));
if(!preg_match("/^[\w\S\s]*$/", $contactbox )){
$contactboxerr = "Please enter only valid characters you would use in writing (ex 'abcABC123')";
}
if(strlen($contactbox) > 2000){
$contactboxerr = "Please enter a response with with a max of 2000 characters.";
}
}
}
function clean_data($field){
$field = trim($field);
$field = stripslashes($field);
return $field;
}
function data_post($param){
if (isset($_POST[$param])){
return $_POST[$param];
}
else{
return '';
}
}
?>
With this being the code for the form:
<div class="sidesection" id="survey">
<h3>Contact Form</h3>
<form action="contact.php" method="POST" novalidate>
<span class="required_asterick">* Is Required</span>
<fieldset>
<legend>Contact Us</legend>
<span class="required_asterick">* </span><label>Name:</label><span class="help" data-tooltip="Please enter a valid name (Ex. 'John Doe')"></span><br />
<input type="text" name="firstname" required pattern="[a-zA-Z '']+" maxlength="25" title="Enter only characters from (a-z) and (A-Z)" value="<?php echo "$fullname";?>"><span class="errormessage"><?php echo "$fullnameerr";?></span><br /><br />
<span class="required_asterick">* </span><label>Email:</label><span class="help" data-tooltip="Please enter a valid email with a max of 50 characters. (Ex. 'xxx#yyy.com')"></span><br />
<input type="email" name="email" required maxlength="50" value="<?php echo "$email";?>">
<span class="errormessage"><?php echo "$emailerr"; ?></span><br /><br />
<span class="required_asterick">* </span><label>Reason For Contact:</label>
<select name="reason" required>
<option value=""> </option>
<option value="general">General</option>
<option value="concern">Concern</option>
<option value="feedback">Feedback</option>
</select><span class="help" data-tooltip="Choose a topic for which you are contacting us so we can process your request faster. General is for any broad topics not listed. Concern is for any pressing matter you may have about the Ithaca Apple Harvest Festival. Feedback is for any suggestions or opinions you wish to share with us about our festivals. "></span><span class="errormessage"><?php echo "$reasonerr";?></span><br /> <br />
<span class="required_asterick">* </span><label>What Would You Like To Tell Us?</label><span class="help" data-tooltip="Use this section to write what you are contacting us for."></span><br />
<textarea name="contacttext" rows="7" cols="60" required><?php echo "$contactbox";?></textarea><span class="errormessage"><?php echo "$contactboxerr"; ?></span><br />
<input type="submit" value="Submit" name="submit">
</fieldset>
</form>
You can see I made the form sticky by adding echoes to errors, so I want to keep that if there are errors. However if it is successful, redirect to a success page.
Just check if you have no errors (i.e. your error variables are empty) and use header()
$fullname = $email = $reason = $contactbox = '';
$fullnameerr = $emailerr = $reasonerr = $contactboxerr = '';
if(data_post('submit')){
// your validations go here
// ......
if (empty($fullnameerr) && empty($emailerr) && empty($reasonerr) && empty($contactboxerr)) {
header('Location: success.php');
}
}
You don't have a control to check whether the validation passed or failed. As a suggestion user a boolean variable to indicate it:
if(data_post('submit')){
$valid=true;
if(empty(data_post('firstname'))){
$fullnameerr = "Please enter a valid name";
$valid=false;
}
if(empty(data_post('email'))){
$emailerr = "Please enter a valid e-mail";
$valid=false;
}
//other validations
if($valid){
//validation passed
header('Location: destination.php');
}
}
In addition to #Deimoks answer, you may need to call exit(); after calling the header() function. If you have any code after the header redirection, it could still be executed even you requested a redirection. exit() prevents that. Also, if you get the "headers already sent" error, look into output buffering.

php validation for password in php

Php validation in php for passord:
How to create retype password validation:
help me friends for retype pass validation in php:
$errorMsg = "";
if((!$email) || (!$password)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$email){
$errorMsg .= "--- Email Address";
}
else if(!$password){
$errorMsg .= "--- Password";
}
}
else {
echo"send to email activation";}
This is my form for registration
<tr>
<td><div align="right">Email: </div></td>
<td><input name="email" type="text" value="<?php echo "$email"; ?>" /></td>
</tr>
<tr>
<td><div align="right"> Password: </div></td>
<td><input name="password1" type="password" value="<?php echo "$password"; ?>" />
<font size="-2" color="#006600">(letters or numbers only, no spaces no symbols)</font></td>
</tr>
<tr>
<td><div align="right"> Retype Password: </div></td>
<td><input name="password" type="password" value="<?php echo "$password"; ?>" />
</tr>
<tr>
<td><div align="right"></div></td>
<td><input type="submit" name="Submit" value="Submit Form" /></td>
</tr>
you can check if $password and $password are same
if($_POST['password '] == $_POST['password1']) echo ' Password Matches';
Try this
<?php
$errorMsg = "";
if((!$email) || (!$password)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$email){
$errorMsg .= "--- Email Address";
}
else if(!$password){
$errorMsg .= "--- Password";
}
}
else {
if($_POST['password1']!=$_POST['password']){
$errorMsg .= "Passwords mismatches";
}
else{
echo"send to email activation";
}
}
?>
If you check only the equalness of two passwords, the empty == empty will true, so lets check them in one expression.
Suggestion
define min length of typed password e.g. 5
use isset because in $_POST the variable with 'password' or 'password1' key might be missing, and you'll receive notice message.
now check
...
if(isset($_POST['password']) && isset($_POST['password1']) && strlen($_POST['password']) >=5 && $_POST['password'] === $_POST['password1']) {
// password validated
}
...
also use trim() function getting email, but not password, because whitespaces can be part of password.
so $email = trim($_POST['email']); // removing whitespaces from left and right

JavaScript Pop up password Check

I am trying to make a register form for my website where it asks for a users password once, and when they click submit, a JavaScript box will pop up and ask it from he user again and checks it against the old one and if they are not the same it stays on the join page and tells them passwords don't match. How would I go about doing this?
Here is the HTML document I have:
<h2>New Account Registration.</h2>
<table width="600" cellpadding="1" style="text-align:center;">
<form action="join.php" method="get" >
<tr>
<td colspan="1"><font color="#FF0000"></font></td>
</tr>
<tr>
<td>Company Name:</td>
</tr>
<tr>
<td><input style="background-color: #FFF;" name="companys_name" type="text" placeholder="Google" required /></td>
</tr>
<tr>
<td>First Name:</td>
</tr>
<tr>
<td ><input style="background-color: #FFF;" name="admin_first_name" type="text" placeholder="John" required />
</td>
</tr>
<tr>
<td>Last Name: </td>
</tr>
<tr>
<td>
<input style="background-color: #FFF;" name="admin_last_name" type="text" placeholder="Doe" required />
</td>
</tr>
<tr>
<td>Phone Number:</td>
</tr>
<tr>
<td><input style="background-color: #FFF;" type="tel" name="admin_phone" pattern="[0-9]{3}-?[0-9]{3}-?[0-9]{4}" required placeholder="123-123-1231"></td>
</tr>
<tr>
<td>Website: </td>
</tr>
<tr>
<td><input style="background-color: #FFF;" type="url" id="orderWebsite" placeholder="http://domain.com" /></td>
</tr>
<tr>
<td>Email: </td>
</tr>
<tr>
<td><input style="background-color: #FFF;" type="email" id="orderEmail" placeholder="name#domain.com" required /></td>
</tr>
<tr>
<td> Password: </td>
</tr>
<tr>
<td> <input style="background-color: #FFF;" name="admin_password" type="password" required />
</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Register!" onclick="register()" /></td>
</tr>
</form>
</table>
Here is the PHP page it connects to:
<?php
$errorMsg = "";
// First we check to see if the form has been submitted
if (isset($_POST['companys_name'])){
//Connect to the database through our include
include_once "connect_to_mysql.php";
// Filter the posted variables
$companys_name = preg_replace("[^A-Za-z0-9]", "", $_POST['companys_name']); // filter everything but numbers and letters
$admin_first_name = preg_replace("[^A-Za-z]", "", $_POST['admin_first_name']); // filter everything but letters
$admin_phone = preg_replace("[^0-9]", "", $_POST['admin_phone']);// Filters everything except numbers
$admin_email = preg_replace("[^A-Z a-z0-9]", "", $_POST['admin_email']); // filter everything but spaces, numbers, and letters
$admin_url = preg_replace("[^A-Z a-z0-9]", "", $_POST['admin_url']); // filter everything but spaces, numbers, and letters
$admin_last_name = preg_replace("[^A-Z a-z]", "", $_POST['admin_last_name']); // filter everything but spaces, numbers, and letters
$admin_email = stripslashes($_POST['admin_email']);
$admin_email = strip_tags($admin_email);
$admin_email = mysql_real_escape_string($admin_email);
$admin_password = preg_replace("[^A-Za-z0-9]", "", $_POST['admin_password']); // filter everything but numbers and letters
// Check to see if the user filled all fields with
// the "Required"(*) symbol next to them in the join form
// and print out to them what they have forgotten to put in
if((!$companys_name) || (!$admin_first_name) || (!$admin_phone) || (!$admin_last_name) || (!$admin_email) || (!$admin_password)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$companys_name){
$errorMsg .= "--- Company Name";
} else if(!$admin_first_name){
$errorMsg .= "--- Phone Number 10 Digits";
} else if(!$admin_phone){
$errorMsg .= "--- Phone Number 10 Digits";
} else if(!$admin_last_name){
$errorMsg .= "--- Last Name";
} else if(!$admin_email){
$errorMsg .= "--- Email Address";
} else if(!$admin_password){
$errorMsg .= "--- Password";
}
} else {
// Database duplicate Fields Check
$sql_companys_name_check = mysql_query("SELECT id FROM toc_companys WHERE companys_name='$companys_name' LIMIT 1");
$sql_admin_email_check = mysql_query("SELECT id FROM toc_companys WHERE admin_email='$admin_email' LIMIT 1");
$companys_name_check = mysql_num_rows($sql_companys_name_check);
$admin_email_check = mysql_num_rows($sql_admin_email_check);
if ($companys_name_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your company name is already in use inside our system. Please try another.";
} else if ($admin_email_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our system. Please try another.";
} else {
// Add MD5 Hash to the password variable
//$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO toc_companys (companys_name, admin_first_name, admin_phone, admin_url, admin_last_name, admin_email, admin_password )
VALUES('$companys_name', '$admin_first_name', '$admin_phone','$admin_url','$admin_last_name', '$admin_email','$admin_password', now())") or die (mysql_error());
// Get the inserted ID here to use in the activation email
$id = mysql_insert_id();
// Create directory(folder) to hold each user files(pics, MP3s, etc.)
mkdir("memberFiles/$id", 0755);
// Start assembly of Email Member the activation link
$to = "$admin_email";
// Change this to your site admin email
$from = "admin#5mutny.com";
$subject = "Activate your account!";
//Begin HTML Email Message where you need to change the activation URL inside
$message = '<html>
<body bgcolor="#FFFFFF">
Hi ' . $admin_first_name . ' at ' . $companys_name . ',
<br /><br />
You must complete this step to activate your account with us.
<br /><br />
Please click here to activate now >>
<a href="http://www.testsite.com/activation.php?id=' . $id . '">
ACTIVATE NOW</a>
<br /><br />
Your Login Data is as follows:
<br /><br />
E-mail Address: ' . $admin_email . ' <br />
Password: ' . $admin_password . '
<br /><br />
Thanks!
</body>
</html>';
// end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
$to = "$to";
// Finally send the activation email to the member
mail($to, $subject, $message, $headers);
// Then print a message to the browser for the joiner
print "<br /><br /><br /><h4>OK $firstname, one last step to verify your email identity:</h4><br />
We just sent an Activation link to: $admin_email<br /><br />
<strong><font color=\"#990000\">Please check your email inbox in a moment</font></strong> to click on the Activation <br />
Link inside the message. After email activation you can log in.";
exit(); // Exit so the form and page does not display, just this success message
} // Close else after database duplicate field value checks
} // Close else after missing vars check
} //Close if $_POST
?>
My teacher wants me to make it so when someone clicks register, a JavaScript box will pop up asking the user to retype their password so that it will check vs. the inputbox one and if they are the same it will make their account if not it won't leave the page but it will tell them their passwords are not the same.
Pseudocode via JQuery:
$('#submit').click(function(){
$('#box').show();
});
$('#box > #confirm').click(function(){
var firstInput = $('#firstInput').val();
var secondInput = $('#secondInput').val();
if(!firstInput.equal(secondInput)) {
//do something if they are not the same
}
});
set id for your form, and add a box:
<form id="myform" action="join.php" method="get" >
...
</form>
<div id="box" style="display: none; width: 100px; height: 100px; backgournd-color: #FFFFFF;">
<input id="confirmPassword"/>
<span id="info"></span>
<button id="confirm">confirm</button>
</div
add script in the bottom of your .html
$('#myform').submit(function(){
$('#box').show();
return false; // cancel the submit action
});
$('confirm').click(function(){
if($('input[value="admin_password"]').val().equal($('#confirmPassword').val())) {
$('#myform').submit(); // to submit the form here
} else {
$('#info').text("passwords are not the same!").show().fadeOut(1000);
}
});

cant figure out php contact form verification woes

Hi I got a contact from script the internet that I have been messing around with, only problem is that the verification that I am trying to add to it just doesn't work. Basically in the form it has name, email, number, type and comment. My main verification woes are with the number field I would like it so that if it is empty it echos "no number" and when the person type in letters instead of numbers it will echo "you need to type with numbers". Something like lol. but I’m stuck. Can any of you geniuses help me? Thanks in advance here is the full code below. p.s. sorry about previous post i accidently cut off the script:$
<?php
$nowDay=date("d.m.Y");
$nowTime=date("H:i:s");
$subject = "E-mail from my site!";
if (isset($_POST['submit'])) {
//contactname
if (trim($_POST['name'] == '')) {
$hasError = true;
} else {
$name = htmlspecialchars(trim($_POST['name']));
}
//emailaddress
if (trim($_POST['email'] == '')) {
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i",trim($_POST['name']))) {
$hasError = true;
} else {
$email = htmlspecialchars(trim($_POST['email']));
}
//phonenumber
if (trim($_POST['number'] == ''))
{
$fake_num = true;
}
else if(!is_numeric($_POST['phonenumber']))
{
$fake_num = true;
}
else
{
$number = htmlspecialchars(trim($_POST['number']));
}
//type
$type = trim($_POST['type']);
//comment
if (trim($_POST['comment'] == '')) {
$hasError = true;
} else {
$comment = htmlspecialchars(trim($_POST['comment']));
}
if (!isset($hasError) && !isset($fake_num)) {
$emailTo = 'email#hotmail.com';
$body = " Name: $name\n\n
Email: $email\n\n
Phone number: $number\n\n
Type: $type\n\n
Comment: $comment\n\n
\n This message was sent on: $nowDay at $nowTime";
$headers = 'From: My Site <'.$emailTo.'>'."\r\n" .'Reply-To: '. $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php
if(isset($hasError))
{
echo"<p>form has error</p>";
}
?>
<?php
if(isset($fake_num))
{
echo"<p>wrong num</p>";
}
?>
<?php
if(isset($emailSent) && $emailSent == true)
{
echo "<p><strong>Email Successfully Sent!</strong></p>";
echo "<p>Thank you <strong> $name </strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>";
}
?>
<div id="stylized" class="myform">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="bookingform" id="bookingform">
<h1>Booking form</h1>
<label>
Name
<span class="small"></span>
</label>
<input type="text" name="name" id="name" class="required"/>
<label>
Your email:
<span class="small"></span>
</label>
<input type="text" name="email" id="email" class="required"/>
<label>
Contact Number:
<span class="small"></span>
</label>
<input type="text" name="number" id="number" class="required" />
<label>
Car required:
<span class="small"></span>
</label>
<select name="type" id="type">
<option selected="selected">Manual</option>
<option>Automatic</option>
</select>
<label>
Comment:
<span class="small"></span>
</label>
<textarea cols="" rows="" name="comment" id="comment" class="required"></textarea>
<button type="submit" name="submit">Submit</button>
</form>
</div>
For checking whether a number has been entered you can use:
if (!preg_match('/^?[0-9]{0,10}$/', $_POST['number'])) {
echo "Please enter a valid number"; //Failed to meet criteria
}
Here you can also specify the amount of numbers that would constitute your valid number with the braces {0,10}, in this case, the number can be up to 11 digits long. If you required it to be only 11 digits long, then use {11}.
If you wish to check if a number has been entered at all you can use:
if (empty($_POST['number'])) {
echo "Please enter a valid number"; //Field was left empty
}
PHP does have a built-in email validation function that you can use
filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
which returns true if the entered email is in the correct format.

PHP contact form phone validation of the correct amount of numbers

PHP contact form phone validation of the correct amount of numbers
Hello,
I have this php form that validates the content once submitted a sticky php form is what it is called. It keeps the users data in the input box when an error if found so the user dose not have to re-enter all the data again.
When the phone number is submitted I need it to validate that there are 3 characters/numbers in the first input box then 3 in the next then 4 in the last one.
The way it is now as long as you input numbers in the first input box it over looks the rest of the input boxes for the phone number. So I am looking to add a minimum character/number script in the validation process. I have the form validating that it is a number at this time. I also need it to validate that there is the correct amount of numbers in each input box for the phone as well. I believe this is just changing the elseif statements to just if inside another if but that did not work either. Any help would be very appreciated. The Art Institute only taught so much with PHP, and not this.
This is the particular area of the script that validates the phone number:
//validate the phone number
if(is_numeric($_POST['phone01'])) {
$phone = $_POST['phone01']. '-';
}elseif(is_numeric($_POST['phone02'])) {
$phone .= $_POST['phone02']. '-';
}elseif(is_numeric($_POST['phone03'])) {
$phone .= $_POST['phone03'];
}else{
print '<p class="error">Please enter your Phone Number as 10 Number.</p>';
$validate = FALSE;
}
This is a copy of the whole script for the form itself:
<?php
// This page receives the data from itself and validates as well
//error reporting!
ini_set ('display_errors', 1);
//Shows all possible problem!
error_reporting (E_ALL);
// validate email
function isValidEmail($email){
return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email);
}
//show form
function show_form($firstName='',$lastName='',$businessName='',$email='',$phone01='',$phone02='',$phone03='',$message=''){
?>
<!--The form starts here -->
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contact form" target="_self" id="contact form" dir="ltr" >
<table bgcolor="#000000" width="525" border="0" align="center">
<tr>
<td width="25%" align="right">*First Name:</td>
<td colspan="2" align="left"><input name="firstName" type="text" id="firstName" tabindex="1" size="30" value="<?php if(isset($_POST['firstName'])) { print htmlspecialchars($_POST['firstName']); }?>"/></td>
</tr>
<tr>
<td align="right">*Last Name:</td>
<td colspan="2" align="left"><input name="lastName" type="text" id="lastName" tabindex="2" size="30" value="<?php if(isset($_POST['lastName'])) {print htmlspecialchars($_POST['lastName']); }?>"/></td>
</tr>
<tr>
<td align="right">Business Name:</td>
<td colspan="2" align="left"><input name="businessName" type="text" id="businessName" tabindex="3" size="35" value="<?php if(isset($_POST['businessName'])) {print htmlspecialchars($_POST['businessName']); }?>"/></td>
</tr>
<tr>
<td align="right">*Email: </td>
<td colspan="2" align="left"><input name="email" type="text" id="email" tabindex="4" size="35" value="<?php if(isset($_POST['email'])) {print htmlspecialchars($_POST['email']); }?>"/></td>
</tr>
<tr>
<td align="right">*Phone Number:</td>
<td colspan="2" align="left">
<input name="phone01" type="text" id="phone01" size="3" maxlength="3" tabindex="5"value="<?php if(isset($_POST['phone01'])) {print htmlspecialchars($_POST['phone01']); }?>"/>
- <input name="phone02" type="text" id="phone02" size="3" maxlength="3" tabindex="6"value="<?php if(isset($_POST['phone02'])) {print htmlspecialchars($_POST['phone02']); }?>"/>
- <input name="phone03" type="text" id="phone03" size="4" maxlength="4" tabindex="7" value="<?php if(isset($_POST['phone03'])) {print htmlspecialchars($_POST['phone03']); }?>"/></td>
</tr>
<tr align="center">
<td align="right">*Message:</td>
<td colspan="2" align="left"><textarea name="message" type="text" id="message" tabindex="8" cols="45" rows="4"><?php if(isset($_POST['message'])) {print htmlspecialchars($_POST['message']); }?></textarea>
</td>
</tr>
<tr align="center">
<td> </td>
<td><input name="submit" type="submit" tabindex="9" value="Email" /></td>
<td><input type="reset" name="reset" id="reset" value=" Reset " tabindex="10"/></td>
</tr>
</table>
</form>
<?php
} // end of show_form function
$validate = TRUE;
if($_SERVER['REQUEST_METHOD']!='POST') {
show_form();
} else {
//validate form fields
//validate the first name
if(empty($_POST['firstName'])) {
print '<p class="error">Please enter your First Name.</p>';
$validate = FALSE;
}
//validate the last name
if(empty($_POST['lastName'])) {
print '<p class="error">Please enter your Last Name.</p>';
$validate = FALSE;
}
//validate the enail with email arrary
if(!isValidEmail($_POST['email'])) {
print '<p class="error">Please enter your Email Address in the correct formate.</p>';
$validate = FALSE;
}
//validate the phone number
if(is_numeric($_POST['phone01'])) {
$phone = $_POST['phone01']. '-';
}elseif(is_numeric($_POST['phone02'])) {
$phone .= $_POST['phone02']. '-';
}elseif(is_numeric($_POST['phone03'])) {
$phone .= $_POST['phone03'];
}else{
print '<p class="error">Please enter your Phone Number as 10 Number.</p>';
$validate = FALSE;
}
//validate the message
if(empty($_POST['message'])) {
print '<p class="error">Please enter your Messagee.</p>';
$validate = FALSE;
}
if(!$validate){
print "<p>Please fill in all the fields with an asterisk * next to it and than please try again!</p>";
show_form($_POST['firstName'],$_POST['lastName'],$_POST['businessName'],$_POST['email'],$_POST['phone01'],$_POST['phone02'],$_POST['phone03'],$_POST['message']);
}else{
$phone01 = $_POST['phone01'];
$phone02 = $_POST['phone02'];
$phone03 = $_POST['phone03'];
$phone = $phone01.'-'.$phone02.'-'.$phone03;
//confirmation email to client includes all information provided
mail($_POST['email'], 'Contact Confirmation from www.Ozbar.net Web site', 'Thank You '.$_POST['firstName'].' '.$_POST['lastName'].' for your request for us to contact you.
Below is the information your provided us to contact you per your request.
First Name: '.$_POST['firstName'].'
Last Name: '.$_POST['lastName'].'
Business Name: '.$_POST['businessName'].'
Email Address: '.$_POST['email'].'
Phone Number: '.$_POST['phone01'].'-'.$_POST['phone02'].'-'.$_POST['phone01'].'
Message: '.$_POST['message'].' ','From:contact#steveoatman.me);
//notice of a new contact request
mail('contact#steveoatman.me, 'Contact Request from www.Steveoatman.me Web site', '
First Name: '.$_POST['firstName'].'
Last Word: '.$_POST['lastName'].'
Business Name: '.$_POST['businessName'].'
Email Address: '.$_POST['email'].'
Phone Number: '.$_POST['phone01'].'-'.$_POST['phone02'].'-'.$_POST['phone01'].'
Message: '.$_POST['message'].' ','From:contact#steveoatman.me);
print '<p align="center">Thank You For Your Request!</p>'?><br /><?php
print '<p align="center">We will contact you back with in 24-48 hours.</p>'
?>
<br /><br /> <!-- if all validated a thank you statement -->
<?php
}
} //end of IF submit
// end of all php
?>
<!-- end of #ref form -->
Use strlen to validate the field lengths. Do not use if/elseif as you want to verify all three inputs. Set a flag to keep track of the validity of the phone number.
$invalid_phone = false;
if((strlen($_POST['phone01']) == 3) && is_numeric($_POST['phone01'])) {
$phone = $_POST['phone01']. '-';
}else{
$invalid_phone = true;
}
if((strlen($_POST['phone02']) == 3) && is_numeric($_POST['phone02'])) {
$phone .= $_POST['phone02']. '-';
}else{
$invalid_phone = true;
}
if((strlen($_POST['phone03']) == 4) && is_numeric($_POST['phone03'])) {
$phone .= $_POST['phone03'];
}else{
$invalid_phone = true;
}
if($invalid_phone){
print '<p class="error">Please enter your Phone Number as 10 Number.</p>';
$validate = FALSE;
}
The code above is just checking whether any of the 3 fields have a number in them, rather than all of them.
To achieve what you are going for above, something like this would do it:
if (is_numeric($_POST['phone01']) && is_numeric($_POST['phone02']) && is_numeric($_POST['phone03']))
{
$phone = $_POST['phone01']."-".$_POST['phone02']."-".$_POST['phone03'];
}
else
{
print '<p class="error">Please enter your Phone Number as 10 Number.</p>';
$validate = FALSE;
}
However, the above code does not do any other kind of validation, such as checking to see that the required number of digits have been put in each form field.
You might also want to use the 'ctype_digit()' function to make sure that only digits are entered, rather than a numric string such as 1.3.
So you could do something like
if (!ctype_digit($_POST['phone01']) || strlen($_POST['phone01']) != 4)
{
$validate = FALSE;
}

Categories