validate update form - php

I am creating a page in which I am fetching data from table and showing data in textbox to allow user to update record. I also validate the user input to textbox. But the problem is when the user does not change any field and click on submit, it validates username field i.e. it always wants to change (or edit textbox) the value of textboxes.
Here is my code:
<?php
include("conn.php");
$id=$_GET['id'];
$sql="SELECT * FROM test WHERE id='$id'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
?>
<script type='text/javascript'>
function formValidator()
{
// Make quick references to our fields
alert("hiiiiiii");
var name = document.getElementById('name').value;
var email = document.getElementById('emailid').value;
var ph = document.getElementById('ph').value;
if( name=="" || name==null)
{
alert("Please Enter user name");
return false;
}
var alphaExp = /^[a-zA-Z]+$/;
if(!name.match(alphaExp))
{
alert("please Enter only Alphabates for Name");
return false;
}
if(email=="" || email=="null")
{
alert("Please Enter Email Address");
return false;
}
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(!email.match(emailExp))
{
alert("please Enter valide email address");
return false;
}
if(ph=="" || ph=="null")
{
alert("Please Enter Phone Number");
return false;
}
var numericExpression = /^[0-9]+$/;
if(!ph.match(numericExpression))
{
alert("Enter only Digit for Phone Number");
return false;
}
}
</script>
<form name="updateform" method="POST" action="update_ind_new.php" onsubmit='return formValidator()'>
<table width="200" border="0">
<tr>
<td>User Name</td>
<td>E-Mail</td>
<td>phno</td>
</tr>
<tr>
<td><label>
<input name="name" type="text" id="name" value=" <?php echo $row['name']; ?>" >
</label></td>
<td><label>
<input name="email" type="text" id="emailid" value=" <?php echo $row['emailid']; ?>" >
</label></td>
<td><label>
<input name="ph" type="text" id="ph" value=" <?php echo $row['phno']; ?>" >
</label></td>
</tr>
<tr>
<td> <input name="id" type="hidden" id="id" value=" <?php echo $row['id']; ?>"></td>
<td><label>
<input type="submit" name="Submit" value="Submit">
</label></td>
<td> </td>
</tr>
</table>
</form>

write return true; at the end of this line
if(!ph.match(numericExpression))
{
alert("Enter only Digit for Phone Number");
return false;
}
return true;

Put return true; at the end of all the conditions in the validation function
or put a validations in "if else if else" conditions

Related

How to display a message adjoining a text box in a form?

I have a form named test.php, which contains 2 buttons, each for entering an email id and userid ; and a submit button . When the user clicks on submit button , my code simply checks if the email id exists and displays a message to the user . I would like to display this message adjoining the text box for email id. But when I echo this message just next to the textbox , I get an error message that the variable is not defined ,since it doesn't find the variable each time the form loads . How do I change my code to display the message adjoining the textbox for entering the email id? Is it necessary for me to use sessions?
Here is my code :
<body>
<h3>Registration Form</h3>
<form action ="" method="POST">
<table align="center" cellpadding="10">
<tr>
<td>Email Id</td>
<td><input type="text" maxlength='100' name="emailid" id="emailid" required>
<?php
echo $msgemail;
?>
</td>
</tr>
<tr>
<td>User Id</td>
<td><input type="text" maxlength='100' name="userid" id="userid" required ></td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="Login">
</td>
</tr>
</table>
</form>
</body>
<?php
//create a connection
$conn = mysqli_connect('localhost', 'root', '', 'attendance');
if (isset($_POST['login'])) {
//capture the $_POST value
$email = $_POST['emailid'];
$email = trim($email);
$userid = $_POST['userid'];
$userid = trim($userid);
if ($email=="") {
echo "Please enter a valid email id";
}
if ($userid=="") {
echo "Please enter a valid User Id";
}
//check if the email id exists
$sql_check_email = "select * from employee where emp_email='$email';";
mysqli_query($conn, $sql_check_email);
$aff_email = mysqli_affected_rows($conn);
// if email id exists ..display message
if ($aff_email==1) {
$msgemail = "the email id exists";
} else if ($aff_email>1) {
$msgemail = "there are multiple employees with the same email";
//display error message if there is an error
} else if ($aff_email<0) {
echo "There is an error ..Try again";
}
}
?>
Try setting your $msgemail as a session and just add the check for the session where you want to display the $msgemail.
Remember to delete the session or it will continue showing it.
Sidebar: try using bootstrap for layouts. Better than using tables.
Define $msgemail before if (isset($_POST['login'])) { since you are adding it inside if $msgemail will be killed by PHP after the closing of if }. And put yout PHP code at top before using it in html
Thanks for your inputs . Sessions can definitely address the problem above . However , I tried the same using ajax,php, mysql . I displayed a message in a div tag which i placed just next to the textbox where the email id is entered :
In the onchange event of the textbox for email id , I am using a function showuser that accepts the value of the textbox as a parameter and checks whether the email id exists through ajax and a php file :welcome_user.php . Therefore , everytime a user enters an email id that already exists and moves on to the next textbox input , a message is displayed in the div tag just adjoining the textbox that the "email id exists" .
Here's what I have done :
registration.php:
<!DOCTYPE html>
<html>
<head>
<title>
Registration Form
</title>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","welcome_user.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<h3>Registration Form</h3>
<form action ="test-reg.php" method="POST" enctype="multipart/form-data">
<table align="center" cellpadding="20">
<tr>
<td>Name</td>
<td><input type="text" maxlength='100' name="empname" id="empname" required></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="text" maxlength='100' name="emailid" id="emailid" onchange="showUser(this.value)" required></td>
<td align="left"><div id="txtHint"></div></td></tr>
</tr>
<tr>
<td>User Id</td>
<td><input type="text" maxlength='100' name="userid" id="userid" required ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" maxlength='100' name="pwd" id="pwd" required ></td>
</tr>
welcome_user.php :
<?php
if (isset($_GET['q'])) {
$q = $_GET['q'];
$conn = mysqli_connect('localhost','root','','attendance');
$sql_get_email = "select * from employee where emp_email='$q'";
mysqli_query($conn, $sql_get_email);
$aff_email = mysqli_affected_rows($conn);
if ($aff_email>0) {
echo "Email id exists";
}
}
?>

JS Form Validation Fails, Yet Form Still Submits?

It's pretty much as the question suggests, I have a HTML form with JS validation. Now, I'm still debugging fine details with the validation, but the problem is that the onSubmit function fires the errors when they should be, but the form continues to submit - I have no idea why. I've check the million and one similar problems on StackOverflow, but none seem to have the same cause as mine - I've checked and check and checked. If anyone could help, I'd greatly appreciate it.
Also, I know my code can be shortened, but I'll do that when I figure this problem out.
Form:
<form name="registerForm" method="post" action="index.php" onSubmit="return validateForm()">
<table class="formTable" >
<tr>
<td><i class="smallprint">* denotes a required field.</i></td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtUsrName">
</td>
<td>
User Name* <i class="smallprint"> between 6 and 32 characters (letters, numbers and underscores only)</i><br />
<b class="error" id="userNameError">Error: Please enter a user name between 6 and 32 characters, using letters, numbers and underscores</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtFName">
</td>
<td>
First Name*<br />
<b class="error" id="fNameError">Error: Please enter your first name</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtSName">
</td>
<td>
Surname*<br />
<b class="error" id="sNameError">Error: Please enter your surname</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtEmail">
</td>
<td>
Email* <i class="smallprint">Please use a valid email address, it will be used to validate your account</i><br />
<b class="error" id="emailError1">Error: Please enter an email address<br /></b>
<b class="error" id="emailError2">Error: This is not a valid email address</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtEmailConf">
</td>
<td>
Confirm Email*<br />
<b class="error" id="emailConfError">Error: Both email addresses must match</b>
</td>
</tr>
<tr>
<td>
<input type="password" maxlength="32" width="32" name="regTxtPassword">
</td>
<td>
Password* <i class="smallprint">Between 6 and 32 characters, using at least one letter and one number</i><br />
<b class="error" id="passwordError">Error: Please enter a valid password</b>
</td>
</tr>
<tr>
<td>
<input type="password" maxlength="32" width="32" name="regTxtPasswordConf">
</td>
<td>
Confirm Password*<br />
<b class="error" id="passwordConfError">Error: Both email passwords must match</b>
</td>
</tr>
</table>
<br />
<div class="textCenter">
<input type="checkbox" class="center" name="regChkTos"> - Check this box if you agree to the Terms of Service. You must agree in order to regster.
<br />
<br />
<input type="submit" name="regSubmit" value="Register">
</div>
</form>
JS:
<script type="text/javascript">
function validateForm()
{
var noError = true;
if (!validateUserName())
{
noError = false;
}
if (!validateFName())
{
noError = false;
}
if (!validateSName())
{
noError = false;
}
if (!validateEmail())
{
noError = false;
}
if (!validateConfirmEmail())
{
noError = false;
}
if (!validatePassword())
{
noError = false;
}
if (!validateConfirmPassword())
{
noError = false;
}
return noError;
}
function validateUserName()
{
var userName = document.forms["registerForm"]["regTxtUsrName"];
var regex = /^\w+$/;
if (userName.value==null || userName.value=="" || userName.value.length < 6 || !regex.test(userName.value))
{
userName.style.border = "2px solid red";
document.getElementById('userNameError').style.display="inline";
return false;
}
else
{
userName.style.border = "2px solid #0f0";
document.getElementById('userNameError').style.display="none";
return true;
}
}
function validateFName()
{
var name = document.forms['registerForm']['regTxtFName'];
if (name.value == null || name.value == '')
{
name.style.border = "2px solid red";
document.getElementById('fNameError').style.display="inline";
return false;
}
else
{
name.style.border = "2px solid #0f0";
document.getElementById('fNameError').style.display="none";
return true;
}
}
function validateSName()
{
var name = document.forms['registerForm']['regTxtSName'];
if (name.value == null || name.value == '')
{
name.style.border = "2px solid red";
document.getElementById('sNameError').style.display="inline";
return false;
}
else
{
name.style.border = "2px solid #0f0";
document.getElementById('sNameError').style.display="none";
return true;
}
}
function validateEmail()
{
noError = true;
var email = document.forms['registerForm']['regTxtEmail'];
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (email.value == null || email.value == '')
{
email.style.border = '2px solid red';
document.getElementById('emailError1').style.display='inline';
noError = false;
}
else
{
document.getElementById('emailError1').style.display='none';
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.value.length)
{
email.style.border = '2px solid red';
document.getElementById('emailError2').style.display='inline';
noError = false;
}
else
{
email.style.border = '2px solid #0f0';
document.getElementById('emailError2').style.display='none';
}
}
return noError
}
function validateConfirmEmail()
{
var email = document.forms['registerForm']['regTxtEmail'];
var emailConf = document.forms['registerForm']['regTxtEmailConf'];
if (email.value != emailConf.value)
{
emailConf.style.border = '2px solid red';
document.getElementById('emailConfError').style.display = 'inline';
return false
}
else
{
emailConf.style.border = '2px solid 0f0';
document.getElementById('emailConfError').style.display = 'none';
return true
}
}
function validatePassword()
{
var password = document.forms['registerForm']['regTxtPassword'];
if (password.value == null || password.value == '' || password.value.length < 6 || password.value.search(/\d/) == -1 || password.value.search(/[A-z]/) == -1)
{
password.style.border = '2px solid red';
document.getElementById('passwordError').style.display = 'inline';
return false;
}
else
{
password.style.border = '2px solid 0f0';
document.getElementById('passwordError').style.display = 'none';
return true;
}
}
function validatePasswordConf()
{
var password = document.forms['registerForm']['regTxtPassword'];
var passwordConf = document.forms['registerForm']['regTxtPasswordConf'];
if (password.value != passwordConf.value)
{
passwordConf.style.border = '2px solid red';
document.getElementById('passwordConfError').style.display = 'inline';
return false;
}
else
{
passwordConf.style.border = '2px solid 0f0';
document.getElementById('passwordConfError').style.display = 'none';
return true;
}
}
</script>
Yes, this script is on the HTML page where the form is located. I've left every field blank, clicked submit, the errors pop up temporarily, then action="index.php" is invoked anyway.
Thanks for any help at all.
first you need to know where the bug is.
For that, use console.log on each function.
After, your code can be optimized with a better algorithm and regex.
To know where the problem is check each return of each function.
For the main function I will do somthing like that :
function validateForm(){
if (validateUserName() && validateFName() && validateSName() && validateEmail() && validateConfirmEmail() && validatePassword() && validateConfirmPassword()){
return true;
}
return false;
}
edit : check the value of your main function too.
do you have a link for this page directly ?

Validating a textbox

I am having a table inside a form. I want all the three columns details to be entered by the user. if the user leaves anyone of them, it should show an alert message like "Please enter the name, it cannot be blank". if all the fields are filled then only the insert into should come into act.
<table> <!--cellpadding=15 cellspacing=3-->
<tr><td>Name</td><td>: <input type="text" name="name"></td></tr>
<tr><td>Address</td><td>: <input type="text" name="address"></td></tr>
<tr><td>Phone No</td><td>: <input type="text" name="dept_id"></td></tr>
</table>
Try to use a flag variable.
<input type="text" name="name" id="nameId">
<input type="text" name="address" id="addressId">
<input type="text" name="dept_id" id="dept_id">
Call this method in onSubmit()
function validate()
{
var validate = false;
if(document.getElementById("nameId").value == "")
{
alert("NAME IS REQUIRED");
validate = true;
}
...................
...................
return validate ;
}
$name = trim($_POST['name']);
if (empty($name))
echo 'name is empty';
do this for rest of the fields
<form method="get" enctype="text/plain"action="">
<table> <!--cellpadding=15 cellspacing=3-->
<? if($_GET['name'] == "") print "Please enter the name, it cannot be blank"; ?>
<tr><td>Name</td><td>: <input type="text" name="name"></td></tr>
<? if($_GET['address'] == "") print "Please enter the Address, it cannot be blank"; ?>
<tr><td>Address</td><td>: <input type="text" name="address"></td></tr>
<? if($_GET['dept_id'] == "") print "Please enter the Phone No, it cannot be blank"; ?>
<tr><td>Phone No</td><td>: <input type="text" name="dept_id"></td></tr>
</table>
</form>
and don't forget to properly escape user input!!!
You can use javascript validation on form submit. Look at it below example.
myForm is form name , onSubmit call function validateForm()
function validateForm()
{
if (document.myForm.name.value == "")
{
alert("Please enter the name");
document.myForm.name.focus();
return false;
}
if (document.myForm.address.value == "")
{
alert("Please enter the address");
document.myForm.address.focus();
return false;
}
if (document.myForm.dept_id.value == "")
{
alert("Please enter the department id");
document.myForm.dept_id.focus();
return false;
}
return true;
}
your complete code
<script type="text/javascript">
function validateForm()
{
if (document.test.name.value == "")
{
alert("Please enter the name");
document.test.name.focus();
return false;
}
if (document.test.address.value == "")
{
alert("Please enter the address");
document.test.address.focus();
return false;
}
if (document.test.dept_id.value == "")
{
alert("Please enter the department id");
document.test.dept_id.focus();
return false;
}
return true;
}
</script>
<form method="post" name="test" onsubmit="return validateForm();">
<table> <!--cellpadding=15 cellspacing=3-->
<tr><td>Name</td><td>: <input type="text" name="name"></td></tr>
<tr><td>Address</td><td>: <input type="text" name="address"></td></tr>
<tr><td>Phone No</td><td>: <input type="text" name="dept_id"></td></tr>
<tr><td colspan="2"><input type="submit" name="submit_form" /></td></tr>
</table>
</form>
$(function() {
$("#registration_form").validate({
rules: {
name: {
required: true,
lettersonly:true
},
contact: {
required: true,
numbers:true,
minlength:10,
maxlength:11
}
}
messages: {
name: {
required: "<h4><span style='color:red'>Please Enter your Name</span></h4>",
lettersonly: "<h4><span style='color:red'>Numbers And Symbols Not Allowed</span></h4>"
},
contact: {
required: "<h4><span style='color:red'>Please Enter your Phone number</span></h4>",
numbers: "<h4><span style='color:red'>Character And Symbols Are Not Allowed</span></h4>",
minlength: "<h4><span style='color:red'>Your phone Number Must Be At Least 10 Characters Long</span></h4>",
maxlength: "<h4><span style='color:red'>Please Enter No More Than 11 Numbers</span></h4>"
}
}
submitHandler: function(form) {
form.submit();
}
}); });
jQuery.validator.addMethod("numbers", function(value, element) {
return this.optional(element) || /^[0-9]+$/i.test(value);
}, "numbers only please");
the name is the id of Name field and contact is the id of Phone number Field.
You can use HTML for this kind of validation.
<input type="text" name="name" required>
When the user fails to fill this field , while submitting it will show a pop up message saying Please fill out this field.

Form not triggering javascript onsubmit event

I have created a "signup" page on my site, but the javascript validation function does not seem to call when the "onsubmit" event is fired. I have already read the posts on this site regarding a similar issue, but their problem seems to be that they forgot to return a boolean value indicating to go ahead and perform the action. Note that this page is "included" in another page with the php function "include".
<script type="text/javascript">
function validateForm() {
//alert();
var display = document.getElementById('error');
var usernameValue = document.getElementById('username').value;
var passwordValue = document.getElementById('password').value;
var rptPasswordValue = document.getElementById('rptPassword').value;
var emailValue = document.getElementById('email').value;
var aliasValue = document.getElementById('alias').value;
if (usernameValue != '' && passwordValue != '' && rptPasswordValue != '' && emailValue != '' && aliasValue != '') {
if (passwordValue == rptPasswordValue) {
if (usernameValue.length > 32 || aliasValue.length > 32) {
displayError("Username or password is too long (Both fields must contain 32 characters or less)");
} else {
if (passwordValue.length > 32 || passwordValue.length < 4) {
displayError("Password must be between 4 and 32 characters in length.");
} else {
if (emailValue.indexOf('#') == -1 || emailValue.length > 64 || emailValue.length < 6) {
displayError("Please make sure you have entered a valid email. (Emails must be between 6 and 64 characters in length)");
} else {
if (aliasValue < 3 || aliasValue > 32) {
displayError("Your alias must be between 3 and 32 characters in length.");
} else {
return true;
}
}
}
}
} else {
displayError("Please make sure both passwords match.");
}
} else {
displayError("Please make sure each field contains a value.");
}
return false;
}
function displayError(var msg) {
document.getElementById('error').innerHTML = msg;
}
</script>
<h1>Sign Up</h1>
<p>All fields must be filled out in order for an account to be created.</p>
<form onsubmit="return validateForm();" action="register.php" method="post">
<table>
<tr>
<td>
<p class="txtLabel">Username:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="0" id="username" name='username'>
</td>
<td>
<p class="txtLabel">Email Address:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="1" id="email" name='email'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Password:</p>
</td>
<td>
<input type="password" class="defaultTxt" tabindex="2" id="password" name='password'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Repeat Password:</p>
</td>
<td>
<input type="password" class="defaultTxt" tabindex="2" id="rptPassword" name='rptPassword'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Nickname/Alias:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="4" id="alias" name='alias'>
</td>
</tr>
</table>
<p><b id='error' style='color: red'></b></p><br />
<input type="submit" value='' name='submit' class="submitBtn">
</form>
Note that in the validateForm function the alert was used to test if the function was called at all, it isn't.
Any ideas?
function displayError(var msg) {
document.getElementById('error').innerHTML = msg;
}
Replace it with
function displayError(msg) {
document.getElementById('error').innerHTML = msg;
}
In your java-script function you cant write like function displayError(var msg).
Good luck.
Bug in your JavaScript here:
function displayError(var msg) {
^^^
document.getElementById('error').innerHTML = msg;
}
You do not need the var keyword in a methods parameters.

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