Reputation: 1598
Hi please excuse the rookie question as I am still very much learning PHP. Im trying to do a basic form validation. Im trying to get any errors found upon validation to be displayed in red inside the form field. If no errors are found the form should redirect to a Thank you page.
Ive written a basic validation, but I am now stuck on how to correctly implement it.
My question is:
My code follows:
HTML
<form id="enquire" method="post" action="thankyou.php">
<h2>Test Drive an Audi Today</h2>
<input type="text" value="Name" class="textbox" id="name" name="name" onfocus="if(this.value=='Name') this.value='';" /><br />
<br />
<input type="text" value="Surname" class="textbox" id="surname" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<br />
<input type="text" value="Contact Number" class="textbox" id="nr" name="nr" onfocus="if(this.value=='Contact Number') this.value='';" /> <br />
<br />
<input type="text" value="Email" class="textbox" id="email" name="email"onfocus="if(this.value=='Email') this.value='';" /><br />
<br />
<select id="swapImg" name="model" class="modelSelect" onchange="swapImage()" >
<option value="images/1.jpg">A4</option>
<option value="images/2.jpg" selected="selected">A6</option>
<option value="images/3.jpg">A8</option>
</select>
<br />
<br />
<input type="submit" name="submit" class="butt" value="Send" />
<span class="buttonText">We'll Call you Back!</span>
</form>
PHP
if (isset($_POST['enquire'])){
//condition
$correct = false;
//Get Info
$name = $_POST['name'];
$surname = $_POST['surname'];
$number = $_POST['nr'];
$email = $_POST['email'];
$_REQUEST['model'];
//name fields
$string_exp = "/^[A-Za-z .'-]+$/";
//email field
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
//validate name field
if($name == ""){
$name_error="* Please enter your name";
$correct = false;
}
else if (!preg_match($string_exp,$name)) {
$name_error= "* Wrong Format";
$correct= false;
}
//validate surname
if($surname == ""){
$surname_error= "* Please enter your surname.";
$correct= false;
}
else if(!preg_match($string_exp,$surname)){
$surname_error= "* Wrong Format";
$correct = false;
}
//check email
if($email==""){
$email_error="* Please enter your email";
$correct = false;
}
else if(!preg_match($email_exp,$email)){
$email_error = "* Wrong Format";
$correct = false;
}
//check number
if($number=""){
$phone_error = "* Please enter your phone number";
$correct = false;
}
else if(!is_numeric($number)){
$phone_error ='* Please enter only numbers 0-9.';
$correct = false;
}
//proceed if all fields validate
if($correct){
$email_to = "[email protected]";
$subject ="New Enquiry";
//set message
$email_message .= "First Name: ".($name)."\n";
$email_message .= "Last Name: ".($lastname)."\n";
$email_message .= "Email: ".($email)."\n";
$email_message .= "Telephone: ".($telephone)."\n";
$email_message .= "Model: ".($model)."\n";
// create email headers
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
@mail($email, $email_subject, $email_message, $headers);
header("thankyou.php");
exit();
}//end if
}// end isset
if anyone could point me in the right direction it would be greatly appreciated.
Upvotes: 1
Views: 10577
Reputation: 156
Javascript would be the best way to accomplish this, however it is possible to do it without it. In order to accomplish it, you would have to use a self-targeting form rather than an outside script. This means the action attribute of the form
is the script it self. Here is an example of the basic layout for the self targeting form:
<?php
if(isset($_POST)){
$correct = true;
//ENTER VERIFICATION CODE HERE. IF AN ELEMENT VERIFIES, LEAVE IT BE. IF AN ELEMENT DOES NOT VERIFY, CHANGE THE POST VALUE TO THE ERROR MESSAGE.
if($_POST['number']=""){
$_POST['number'] = "* Please enter your phone number";
$correct = false;
}else if(!is_numeric($_POST['number'])){
$_POST['number'] ='* Please enter only numbers 0-9.';
$correct = false;
}
//AND SO ON FOR ALL INPUT ELEMENTS
if($correct){
//SEND EMAIL CODE HERE
}else{
//DISPLAY FORM WITH POST VARIABLES AS THE VALUE ATTRIBUTE
echo "<input type='text' name='number' value='" . $_POST['number'] . "'>";
//AND SO ON FOR ALL FORM ELEMENTS
}
}else{
//DISPLAY FORM AS USUAL
}
Recap of code: If $_POST
is set, verify the data. If an element does not verify change the invalid $_POST
value to the error message, then use those $_POST
values to build the next form. If all elements verify, then send the email. If $_POST
is not set, then display the form as usual because we know that the user has not entered any data yet. Good Luck!
Upvotes: 1
Reputation: 1738
To validate the data in the form without submitting it, you will have to use javascript. Here is a sample:
<form id="enquire" method="post" action="thankyou.php">
<div id='error-box' style='color:red;display:none'></div>
<h2>Test Drive an Audi Today</h2>
<input type="text" value="Name" class="textbox" id="name" name="name" onfocus="if(this.value=='Name') this.value='';" /><br />
<br />
<input type="text" value="Surname" class="textbox" id="surname" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<br />
<input type="text" value="Contact Number" class="textbox" id="nr" name="nr" onfocus="if(this.value=='Contact Number') this.value='';" /> <br />
<br />
<input type="text" value="Email" class="textbox" id="email" name="email"onfocus="if(this.value=='Email') this.value='';" /><br />
<br />
<select id="swapImg" name="model" class="modelSelect" onchange="swapImage()" >
<option value="images/1.jpg">A4</option>
<option value="images/2.jpg" selected="selected">A6</option>
<option value="images/3.jpg">A8</option>
</select>
<br />
<br />
<input type="submit" name="submit" class="butt" value="Send" />
<span class="buttonText">We'll Call you Back!</span>
</form>
<script type='text/javascript'>
var name=document.getElementById('name');
if (name.value == null || name.value==""){
errors['no_name']="Please enter your name";
}
//Repeat something similar for each field
//Display all errors on the same page in the error box
error_box=document.getElementById('error-box');
for(error in errors){
error_box.innerHTML=error.value + "<br/>";
}
</script>
Upvotes: 1
Reputation: 24276
You have to use javascript in order to validate the inputs of the form.
If you want to use PHP validation, then an AJAX request should be made.
See the following example using jquery:
$('#enquire').submit(function(e){
e.preventDefault()
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data) {
if (data.isError) {
// do something with the error messages or other parameter
console.log(data.errorMessages);
} else {
// make redirection
document.location.href = "thankyou.php"
}
},
'json'
);
});
in your PHP code you must output data like this:
$errorMessages = array();
if($name == ""){
$errorMessages[] = "* Please enter your name";
}
else if (!preg_match($string_exp,$name)) {
$errorMessages[] = "* Wrong Format";
}
//validate surname
if($surname == ""){
$errorMessages[] = "* Please enter your surname.";
}
else if(!preg_match($string_exp,$surname)){
$errorMessages[] = "* Wrong Format";
}
// after all validations return the results or continue registering the user
if (!empty($errorMessages)) {
die(json_encode(array('isError' => true, 'errorMessages' => $errorMessages)));
}
// continue here the registration
Upvotes: 2
Reputation: 400
This is not a php issue. PHP is a server-side scripting tool which inherently means you need to send data to a server for PHP to be of use.
As mentioned by others you're most likely to be best served with a JavaSript Library A very common and useful one is J-Query Validate but , to be sure, there are many others.
Upvotes: 1
Reputation: 268
You must use javascript to validate on browser side.
You can use pure javascript or a jquery plugin:
Javascript
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
Get more informations here: http://www.w3schools.com/js/js_form_validation.asp
Using Jquery you can use this: http://jqueryvalidation.org/files/demo/
Upvotes: 0