How to automatically focus cursor on input field after PHP validation - php

How can I automatically focus the cursor on an input field after PHP validation. If user enters an incorrect answer, I want to focus on that field when the page loads.
I'm new to PHP. How can I do this in PHP?
Contact Form:
<form method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset style="width:960px; background-color:#FFF; border-radius:10px; padding:50px;">
<legend><h2>Contact Us</h2></legend>
<br />
<fieldset style="border-radius:10px; padding:50px 0px 50px 50px;;";>
<div style="width:275px; height:300px; float:right; padding:30px"><img src="images/contactus.jpg" width="275" height="300" alt="contactus" /></div>
<label>Name:</label>
<input class="txt" type="text" name="name" value="<?php echo isset($_POST['name']) ? htmlentities($_POST['name']) : ''; ?>"/><span class="error"><?php echo $nameErr?></span><br /><br />
<label>Email:</label>
<input class="txt" type="text" name="email" value="<?php echo isset($_POST['email']) ? htmlentities($_POST['email']) : ''; ?>"/><span class="error"><?php echo $emailErr?></span><br /><br />
<label>Mobile No:</label>
<input class="txt" type="text" name="mobileno" value="<?php echo isset($_POST['mobileno']) ? htmlentities($_POST['mobileno']) : ''; ?>"/><span class="error"><?php echo $mobilenoErr?></span><br /><br />
<label>Message:</label>
<textarea class="txt" name="message"rows="5"><?php echo $message?></textarea><span class="error"><?php echo $messageErr?></span><br /><br />
<input style="margin-left:100px; padding:5px 20px 5px 20px; border-radius:5px" type="submit" value = "Submit" />
</fieldset>
</fieldset>
</form>
Contact form validation in PHP:
<?php
if(isset($_POST['name']))
{
include_once("config.php");
$name=$email=$mobileno=$message=="";
$nameErr=$emailErr=$mobilenoErr=$messageErr="";
function test_input($data)
{
$data=trim($data);
$data-stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if($_SERVER['REQUEST_METHOD']=="POST")
{
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["mobileno"]))
{
$mobilenoErr="* Mobile no is Required";
$valid=false;
}
else
{
$mobileno=test_input($_POST["mobileno"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$mobileno))
{
$mobilenoErr="*Enter a valid contact no";
$valid=false;
}
}
//bank name validation
if(empty($_POST["message"]))
{
$messageErr="* Message is Required";
$valid=false;
}
else
{
$message=test_input($_POST["message"]);
}
}
if($valid)
{
echo "Send mail code";
}
}
?>

You can try autofocus (http://diveintohtml5.info/forms.html):
<input class="txt" type="text" name="name"
value="<?php echo isset($_POST['name']) ? htmlentities($_POST['name']) : ''; ?>"
<?php if(!empty($nameErr)) { ?> autofocus <?php } ?>
/>
<span class="error"><?php echo $nameErr?></span><br /><br />

This is just the html option autofocus.
Here you can find a good explanation
<input type="text" name="fname" autofocus>
Or you can do it with javascript, if the IE makes some problems or you arn't coding with html5:
<body OnLoad='document.getElementById("txt").focus();'>
But if you want to do it like this, you must set an id to your inputfield.

The HTML5 autofocus feature with if logic as suggested by Ramesh is correct; however the code is not quite right for an if statement mixed with html. Instead of the normal braces, you need to use a colon and add the php endif statement. Try this:
<input class="txt" type="text" name="name"
value="<?php echo isset($_POST['name']) ? htmlentities($_POST['name']) : ''; ?>"
<?php if(!empty($nameErr)): ?> autofocus <?php endif; ?>
/>
<span class="error"><?php echo $nameErr; ?></span><br /><br />

Related

Form validation issue PHP

I need to create a form, which will check if the input is empty or not. If it is empty there should be a text like "Required field". There is a notice saying, that surName has an undefined index.
Here is my PHP code
<?php
$name_error="";
$sname_error="";
$f_name="";
$s_name="";
if (isset($_POST['submit_button'])) {
if ($_POST['firstName']!=='') {
$f_name=$_POST['firstName'];
}
else {
$name_error="Required Field *";
}
}
if ($_POST['surName']!=='') {
$s_name=$_POST['surName'];
}
else {
$sname_error="Please fill this out";
}
?>
<html>
<head>
<title>Registration form</title>
</head>
<body>
<div class="head">
<p>Registration Form</p>
</div>
<form action="Register/final.php" method="POST">
<label for="firstName">First Name</label><br>
<input type="text" name="firstName" placeholder="First Name" value="<?php echo $f_name; ?>"><br><br>
<p style="color: red;"><?php echo $name_error; ?></p>
<label for="surName">Last Name</label><br>
<input type="text" name="surName" placeholder="Last Name" value="<?
php echo $s_name;?>"><br><br>
<p style="color: red;"><?php echo $sname_error;?></p>
</form>
</body>
</html>
well for starters, you could use the built-in HTML5 input validator required
<input type="text" required>
This will provide that nice user message on submit asking them to please fill out that field.
Secondly, you can check on the server using empty instead of if ($_POST['surName']!=='')
if ( !empty($_POST['surName']) ) {
// your logic here
}
The functionality is basically there already...
I guess the } bracket for if (isset($_POST['submit_button'])) { should be just before ?>
There is missing something like <input type="submit" name="submit_button" value="Register">
And considering what Jeff Puckett II says
So, if I do the changes 1 and 2 to your code, it might look like this:
<?php
$name_error="";
$sname_error="";
$f_name="";
$s_name="";
if (isset($_POST['submit_button'])) {
if ($_POST['firstName']!=='') {
$f_name = $_POST['firstName'];
} else {
$name_error="Required Field *";
}
if ($_POST['surName']!=='') {
$s_name = $_POST['surName'];
} else {
$sname_error="Please fill this out";
}
}
?>
<html>
<head>
<title>Registration form</title>
</head>
<body>
<div class="head">
<p>Registration Form</p>
</div>
<form action="Register/final.php" method="POST">
<label for="firstName">First Name</label><br>
<input type="text" name="firstName" placeholder="First Name" value="<?php echo $f_name; ?>"><br><br>
<p style="color: red;"><?php echo $name_error; ?></p>
<label for="surName">Last Name</label><br>
<input type="text" name="surName" placeholder="Last Name" value="<?php echo $s_name;?>"><br><br>
<p style="color: red;"><?php echo $sname_error;?></p>
<input type="submit" name="submit_button" value="Send">
</form>
</body>
</html>
It is because you've put the surName validation outsite of submit conditional;
`
if (isset($_POST['submit_button'])) {
if ($_POST['firstName']!=='') {
$f_name=$_POST['firstName'];
}else{
$name_error="Required Field *";
}
if ($_POST['surName']!=='') {
$s_name=$_POST['surName'];
}
else{
$sname_error="Please fill this out";
}
}
?>`
Your can improve this a little bit by using an associative array like this errors = array(); and then $errors['surName'] = "this is field is required";
You don't have a submit button. Another thing is that you didn't use your if statement of $_POST['surName'] after submit. You can use it like this :
<?php
error_reporting(1);
$name_error = "";
$sname_error = "";
$f_name = "";
$s_name = "";
if (isset($_POST['submit_button']))
{
if ($_POST['firstName'] != '')
{
$f_name = $_POST['firstName'];
}
else
{
$name_error = "Required Field *";
}
if ($_POST['surName'] != '')
{
$s_name = $_POST['surName'];
}
else
{
$sname_error = "Please fill this out";
}
}
?>
<html>
<head>
<title>Registration form</title>
</head>
<body>
<div class="head">
<p>Registration Form</p>
</div>
<form action="Register/final.php" method="POST">
<label for="firstName">First Name</label><br>
<input type="text" name="firstName" placeholder="First Name" value="<?php echo $f_name; ?>"><br><br>
<p style="color: red;"><?php echo $name_error; ?></p>
<label for="surName">Last Name</label><br>
<input type="text" name="surName" placeholder="Last Name" value="<?php echo $s_name;?>"><br><br>
<p style="color: red;"><?php echo $sname_error;?></p>
<input type="submit" name="submit_button" value="Register">
</form>
</body>
</html>

how to retain values in text boxes after submit button on click if found error with session

I make a register form and I want when submit button clicked, if some textbox have a problem, other textboxes retain values. I write this code but it's not work and after refresh the website all of the textboxes became null...
<?php
if(isset($_POST['submit'])){
session_start();
$_SESSION['name']=$_POST['name'];
$_SESSION['email']=$_POST['email'];
$name=$_POST['name'];
$email=$_POST['email'];
$pas = hash_value($_POST['pass']);
$pas2 = hash_value($_POST['pass2']);
if(empty($name)|| empty($email)|| empty($pass) || empty($pass2))
{
header("location:register.php?msg=10");
}
?>
and this is my form code:
<form method="post" action="">
<input value="<?php echo isset($_SESSION['name']) ? $_SESSION['name'] : ''; ?>" type="text" name="name" id="name" />
<input value="<?php echo isset($_SESSION['email']) ? $_SESSION['email'] : ''; ?>" type="text" name="email" id="email" />
<input type="password" name="pass" id="pass" />
<input type="password" name="pass2" id="pass2" />
</form>
<?php
if(isset($_GET['msg'])){
$msg = $_GET['msg'];
switch($msg){
case 10;
$err ="please check all of the textboxes!";
$color = "red";
$colorback = "#ffd0e2";
break;
}
echo '<div id="error" style="text-align:center; padding:5px 0; margin:0px 0 10px 0;; width:98%;background-color:'.$colorback.'; color:'.$color.'">'.$err.'</div>;
}

Why is my php files not responding to the css file linked to it?

I'm trying to change to color of the error alerts on this php file. By my css files doesn't seems to respond. Can you help me figure out the reason? I'd like to make my alerts blue and bigger.
Here's the form :
<div id="dv_global_form">
<form action="index.php" method="post">
<p class="required">Required fields *</p>
Name:<input type="text" name="name" <?php echo"value='$nameValue'"?>> <span class="required"> *</span><?php echo"<span class='required'> $nameErr</span>" ;?></span><br>
Surname:<input type="text" name="surname"<?php echo"value=$surnameValue"?>><span class="required"> *</span><?php echo"<span class='required'> $surnameErr</span>" ;?></span><br>
Date of Birth:<select name="dob">
<?php dob()?>
</select><span class="required"> *</span><?php echo"<span class='required'> $dobErr</span>" ;?><br>
Email:<input type="email" name="email" <?php echo"value=$emailValue"?>><span class="required"> *</span><?php echo"<span class='required'> $emailErr</span>" ;?>
<h3>Gender<span class="required"> * </span></h3>
<input type="radio" name="gender" value="male">Male<br>
<input type="radio" name="gender" value="female">Female<br>
<input type="submit" value="submit">
</form>
<?php echo"<p class='required' > $genderErr</p>" ;?>
</div>
Here's the php file containing the functions:
function dob(){
echo "<option></option>";
for($i=1989;$i<2001;$i++){
if($i==$_POST['dob']){
echo "<option selected='selected'>$_POST[dob]</option>";
}else{
echo "<option>$i</option>";
}
}
}
// Validate fields
$nameErr= $surnamErr=$emailErr= $dobErr=$sexErr=$genderErr="";
$nameValue=$surnameValue=$dobValue=$emailValue="";
if($_SERVER["REQUEST_METHOD"]==POST){
if(empty($_POST['name'])){
$nameErr="Name is required field";
}else{
if(!preg_match("/^[a-zA-Z\s]*$/",$_POST['name'])){
$nameErr="Only letters and white space allowed";
}else{
$nameValue=$_POST['name'];
}
}
if(empty($_POST['surname'])){
$surnameErr="Surname is required field";
}else{
if(!preg_match("/^[a-zAZ]*$/",$_POST['surname'])){
$surnameErr="Only letters and white space allowed";
}else{
$surnameValue=$_POST['surname'];
}
}
if(empty($_POST['dob'])){
$dobErr="Date of birth is required field";
}
if(empty($_POST['email'])){
$emailErr="Email is a required filed";
}else{
if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
$emailErr="This email format is not valid";
}
$emailValue=$_POST['email'];
}
if(empty($_POST['gender'])){
$genderErr="Gender is a required field";
}else{
}
}
And here's the css :
.required{
color:blue;
}
#gender{
color:blue;
}

header, session, php validation

I'm having a big problem with my validation form. Basically I created a form that will, once submitted, redirect to another page. To do this I used header("location: aaaaa.php") and apparently it works. The problem is that by doing this the validation doesn't work anymore, in fact if I don't enter any data and press submit I'll be redirected to the second page without getting the errors. If I delete the header the validation works again.
Moreover I have a big problem with the session method. I tried different way of using it to transfer the data to the second page when pressed the button submit, but it doesn't work and no one until now was able to help me. In the code that I'm gonna put below I deleted the session method and I was hoping that you would help me with that.
London Flight Agency
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name =($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname =($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email =($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["telephone"])) {
$telephoneErr = "Number is required";
} else {
$telephone =($_POST["telephone"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9\_]{7,20}/",$telephone)) {
$telephoneErr = "Enter correct telephone number";
}
}
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$date =($_POST["date"]);
// check if name only contains letters and whitespace
if (!preg_match("~^\\d{1,2}[/.-]\\d{2}[/.-]\\d{4}$~",$date)) {
$dateErr = "Enter correct date of birth";
}
}
if (empty($_POST["luggage"])) {
$luggageErr = "Choose one of the options";
} else {
$luggage =($_POST["luggage"]);
}
$weight = $_POST['weight'];
$height = $_POST['height'];
if(isset($_POST['submit']))
{
$total = ($weight+$height)/10;
}
header("Location: thankyou.php");
}
?>
<h2 id="title">London Flight Agency</h2><!-- This tag is used to define HTML heading (h1 to h6), this particular one defines the most important heading -->
<form id="form" method="post" name="myForm" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return validateForm(this);"><!-- The <form> tag is used to create an HTML form for user input -->
<h4 class="subtitle"><strong>Personal Details</strong></h4>
<fieldset>
Enter here all your details (all of them are compulsory.)
<br />
<br />
<select name="Title" id="title" value="<?php echo $title;?>" onblur="validateSelect(name)">
<option value="empty">Title</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Dr">Dr</option>
</select><br /><br />
<span class="validateError" id="titleError" style="display: none;">You must select a title!</span>
<span id="error8"><?php echo $titleErr;?></span>
<table
<tr>
<td><label for="firstname">First Name:</label></td>
<td><input type="text" name="name" value="<?php echo $name;?>" id="name" onblur="validateName(name)"></td>
<span id="nameError" style="display: none;"></span>
<span id="error1"><?php echo $nameErr;?></span>
</tr>
<tr>
<td><label for="surname">Surname:</label></td>
<td><input type="text" name="surname" value="<?php echo $surname;?>" id="name" onblur="validateSurname(surname)"></td>
<span id="surnameError" style="display: none;"></span>
<span id="error2"><?php echo $surnameErr;?></span>
</tr>
<tr>
<td><label for="email">Email address:</label></td>
<td><input type="text" name="email" value="<?php echo $email;?>" id="email" onblur="validateEmail(email)"></td>
<span id="emailError" style="display: none;"></span>
<span id="error3"><?php echo $emailErr;?></span>
</tr>
<tr>
<td><label for="telephone">Telephone No:</label></td>
<td><input type="text" name="telephone" value="<?php echo $telephone;?>" id="telephone" onblur="validateTelephone(telephone)"></td>
<span id="telephoneError" style="display: none;"></span>
<span id="error4"><?php echo $telephoneErr;?></span>
</tr>
<tr>
<td><label for="date">Date of birth:</label></td>
<td><input type="text" name="date" value="<?php echo $date;?>" id="date" onblur="validateDate(date)"></td>
<span id="dateError" style="display: none;"></span>
<span id="error5"><?php echo $dateErr;?></span>
</tr>
</table>
</fieldset>
<h4 class="subtitle"><strong>Flight Details</strong></h4>
<fieldset>
<p>Hand luggage:</p><br />
<input type="radio" name="luggage" <?php if (isset($luggage) && $luggage=="Yes") echo "checked";?>value="Yes" id = "myRadio" required onblur="myFunction()">Yes
<input type="radio" name="luggage" <?php if (isset($luggage) && $luggage=="No") echo "checked";?>value="No" id = "myRadio" required onblur="myFunction()">No
<span id="luggageError" style="display: none;"></span>
<span id="error6"><?php echo $luggageErr;?></span>
<br /><br />
<label for="extrabag">Include free extra bag</label>
<input type="checkbox" name="extra" id="check" value="bag">
<br />
<br />
<select name="option" id="card" onblur="validatePayment(card)">
<option value="empty">Payment Card</option>
<option value="Visa">Visa Debit Card</option>
<option value="MasterCard">MasterCard</option>
<option value="PayPal">PayPal</option>
<option value="Maestro">Mestro</option>
<option value="Visa Electron">Visa Electron</option>
</select><br />
<span class="validateError" id="cardError" style="display: none;">You must select your payment card!</span>
</fieldset>
<h4 class="subtitle"><strong>Luggage Details</strong></h4>
<fieldset>
<p>Enter weight and height of your luggage.</p>
Your Weight(kg): <input type="text" name="weight" size="7"><br />
Your Height(cm): <input type="text" name="height" size="7"><br />
<span id="error7"><?php echo $measureErr;?></span>
<input type="button" value="Tot. price" onClick="totalPrice()"><br /><br />
Total Price: <input type="text" name="total" value="<?php echo $total?>" size="10"><br /><br />
<input type="reset" value="Reset">
<input type="submit" value="Submit" name="submit">
</fieldset>
</form>
</body>
It doesn't show the first part of the code for I don't know which reason. I'll post it below:
London Flight Agency
The problem Is that you are checking if the method is post then redirect to the new page.
You must check if the your entries are valid then redirect.
For Example You can make an array of data and use array_push to push new data whenever there is something invalid and then check like this :
if( count( $array ) == 0 )
header('Location:YOUR_NEW_PAGE.php');
This is one of the simplest solutions you can implement.
Good luck

php contact form validation which stops showing form on no errors and success

Here's my code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yourname"])) {
$yournameErr = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I have got to the point where it doesn't show errors but I probably didn't explain myself too clearly. After the point at which it doesn't show error messages anymore, I would like the form to no longer appear and then I can put something down like "Successful." However I can't seem to achieve this.
my form is :
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br />
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1; border-color:#000000; " />
<span class="error">* <?php echo $yournameErr;?></span>
</div>
<br />
<br />
<div>
<label> Email :</label> <br />
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1; border-color:#000000; " />
<span class="error">* <?php echo $emailErr;?></span>
</div>
<br />
<br />
<div>
<label> Subject : </label><br />
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1; border-color:#000000; " />
</div>
<br />
<br />
<div>
<label> Message :<br /> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message"
placeholder="The message you want to send to us." style="border:1; border-
color:#000000 " >
</textarea>
<span class="error">* <?php echo $messageErr;?></span>
</div>
<br />
<br />
<div>
<input type="submit" name="button" id="button" style="border:1; border-
color:#999999; " value="SEND"/>
</div>
</form>
What if you put your errors in an array and put a condition that check that array size and if it is 0 (no errors) echo the success message and don't show the form else join the errors and print it out.
Maybe like this:
contact.php
<?php
$error = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yourname"])) {
$error['name'] = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
if (empty($_POST["email"])) {
$error['email'] = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$error['email'] = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$error['message'] = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if (!count($error)) {
$noError = true;
}
}
$successMessage = isset($noError) ? 'Successful.' : '';
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function getErrorMessage($type, $error)
{
return isset($error[$type]) ? $error[$type] : '';
}
if ($successMessage) {
echo $successMessage;
} else {
?>
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br/>
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1px; border-color:#000000; "/>
<span class="error">* <?php echo getErrorMessage('name', $error); ?></span>
</div>
<br/>
<br/>
<div>
<label> Email :</label> <br/>
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1px; border-color:#000000; "/>
<span class="error">* <?php echo getErrorMessage('email', $error); ?></span>
</div>
<br/>
<br/>
<div>
<label> Subject : </label><br/>
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1px; border-color:#000000; "/>
</div>
<br/>
<br/>
<div>
<label> Message :<br/> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message"
placeholder="The message you want to send to us." style="border:1px; border-
color:#000000 "></textarea>
<span class="error">* <?php echo getErrorMessage('message', $error); ?></span>
</div>
<br/>
<br/>
<div>
<input type="submit" name="button" id="button" style="border:1px; border-
color:#999999; " value="SEND"/>
</div>
</form>
<?php } ?>
According to your code, I'm going to assume that your contact.php is posting to itself. In other words, your PHP code is located above your HTML --as a result of your question that the contact form no longer renders after a request. That is, once the server renders the page, the form tag will not display because there are no errors in the submission or the super global $_POST has been set.
I've slightly altered your code for readability. I included an array that will hold all your error messages throughout your form validation. If there are no errors, then we can simulate a successful submission and thus reflect this result on response. Your form will only display if there are errors OR the post has not been submitted.
Inside your form, you need an input tag of submit. Furthermore, only if errors are indeed set, that we want to display an error specific message. That is why a condition is set for your span tags. Lastly, I included the same condition in your values -an additional feature for remembering what you have entered.
If the form is successfully submitted, then don't render the form tag and, instead, display a message of success along with all the POST data!
<?php
if (isset($_POST['submit'])) {
$error_message = array();
if (empty($_POST["yourname"])) {
$error_message['yournameErr'] = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
if (empty($_POST["email"])) {
$error_message['emailErr'] = "Email is required";
} elseif (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $_POST["email"])) {
$error_message['emailErr'] = "Invalid email format";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["message"])) {
$error_message['messageErr'] = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if(empty($error_message)) {
// process data from post
$successful = true;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php if(!empty($error_message) || !isset($_POST['submit'])) : ?>
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br />
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1; border-color:#000000; " value="<?php if(isset($yourname)) {echo $yourname; }?>" />
<span class="error">* <?php if(isset($error_message['yournameErr'])){echo $error_message['yournameErr']; }?></span>
</div>
<br />
<br />
<div>
<label> Email :</label> <br />
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1; border-color:#000000; " value="<?php if(isset($email)) { echo $email;}?>" />
<span class="error">* <?php if(isset($error_message['emailErr'])) {echo $error_message['emailErr'];}?></span>
</div>
<br />
<br />
<div>
<label> Subject : </label><br />
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1; border-color:#000000; " />
</div>
<br />
<br />
<div>
<label> Message :<br /> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message" placeholder="The message you want to send to us." style="border:1; border-color:#000000"></textarea>
<span class="error">* <?php if(isset($error_message['messageErr'])) {echo $error_message['messageErr']; }?></span>
<br>
<input type="submit" name="submit" value="Submit">
</div>
<?php endif; ?>
<?php if(isset($successful)) : ?>
<p>Successful</p>
<p>Your name: <?=$yourname;?></p>
<p>Your email: <?=$email;?></p>
<p>Your subject: <?=$_POST['subject']?></p>
<p>Your message: <?=$message;?></p>
Back to form
<?php endif; ?>

Categories