I have a simple PHP page, and am attempting to validate form input.
Upon hitting submit with invalid data, the inputted value is not being returned in my echo statement
I want to echo the input as the value so that the user can understand what they typed wrong. Below is my code;
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
<?php
// define variables and set to empty values
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<!--Begin HTML Form-->
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr;?></span><br> <!--<p class='spacerLine'></p>-->
<input type="text" class="largeInput" name="contactFirstName" value="<?php echo $contactFirstName;?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php echo $contactEmail;?>">
<br><br>
<?php echo "TEST" . $contactEmail;?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php echo $retailerID;?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Any thoughts? I'm new to PHP but have been following the W3 tutorial pretty tightly. Could it be my classes throwing things off? Or did I just mess up a variable name?
Thanks for all help
I want to echo the input as the value so that the user can understand what they typed wrong.
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
First of all, echo $_POST values instead of $contactFirstName, $contactEmail etc. because these values are available only after it crosses all the validation steps.
Second, there's no function named test_input() in your code, or may be it is defined somewhere else.
And finally, look at this statement here:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { ..
There's no variable named $email in your code. It should be:
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) { ..
So your code should be like this:
<?php
function test_input($string){
// your code
}
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr; ?></span><br>
<input type="text" class="largeInput" name="contactFirstName" value="<?php if(isset($_POST['contactFirstName'])){ echo $_POST['contactFirstName']; } ?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; } ?>">
<br><br>
<?php
echo "TEST ";
if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; }
?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php if(isset($_POST['retailerID'])){ echo $_POST['retailerID']; } ?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Here's the reference for isset() function:
isset()
Sidenote: Even though this answer will work you temporarily, but you should definitely look at how to strictly validate form inputs using regex.
The below line validates the value of the variable $email, but i can't see anywhere in your code where does that variable get set a value, that can be the first step in fixing the issue.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
You are not defining test_input() function and $email is not defined in this line:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
This code works for me so far:
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = $_POST["contactFirstName"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = $_POST["contactEmail"];
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = $_POST["retailerID"];
}
}
Related
i would like to save all submitted data into text file.
there is a regex looking for any name error, if there is, there should be an error message AND!! that submission should not be captured into the text file.
result now: if i were to hit submit button even with name being numbers, i am able to submit and the error message did show up, however, it is being captured in the text file.
HOW can i stop it from saving the input if the condition is not met?
<p> <span class="required"> text boxes with * are required field </span></p>
<form method="post">
Name: <input type="text" id="name" name="name">
<span class="required"> * <?php echo $nameErr;?></span>
<br><br>
Phone Number: <input type="text" id="phoneno" name="phoneno">
<span class="required"> * <?php echo $phonenoErr;?></span>
<br><br>
E-Mail: <input type="text" id="email" name="email">
<span class="required"> * <?php echo $emailErr;?></span>
<br><br>
<input type="submit" id="submit" name="submit" value="submit"> <!--need to code submit alr will redirect to where-->
</form>
UPDATED MY CODE
if (isset($_POST['submit'])) {
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["phoneno"])) {
$phonenoErr = "Phone Number is required";
} else {
$phoneno = $_POST["phoneno"];
// check if name only contains letters and whitespace
if (!preg_match("/^[[0-9]{8}]*$/", $phoneno)) {
$phonenoErr = "Please key in 8 digits phone number";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email Address is required";
} else {
$email = $_POST["email"];
// check if name only contains letters and whitespace
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Wrong email format";
}
else {
/* to save html input into text file */
$name = "Seller Name: " . $_POST['name'] . "
";
$phoneno = "Phone Number: " . $_POST['phoneno'] . "
";
$email = "E-Mail: " . $_POST['email'] . "
";
$file = fopen("testing.txt", "a");
fwrite($file, $name);
fwrite($file, $phoneno);
fwrite($file, $email);
fclose($file);
}
}
You do not need an else statement. Right now your file checks "is a form submitted or not" and if it's not, then stuff will be saved. That doesn't make sense, right? You want to save only if the form was submitted! So don't use an else condition.
You can use an error variable to check if there is any error in any user input.
if (isset($_POST['submit'])) { //the user put in data and submitted the form
$error = 0; //no error yet
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$error = 1; //now there is an error
} else {
$name = $_POST["name"]; //be aware of security risks like SQL injection
}
//error checking for other inputs in the same way
//If there is no error at all, then save the input into a file
if ($error == 0) {
/* to save html input into text file */
$save = "Seller Name: " . $name;
$save .= "Phone Number: " . $phoneno;
$save .= "E-Mail: " . $email;
$file = fopen("testing.txt", "a");
fwrite($file, $save);
fclose($file);
}
}
You should put your writing file logic inside your success condition, without changing much of your code, it should be something like this:
$nameErr = $phonenoErr = $emailErr = "";
/*condition®ex to all text field*/
if (isset($_POST['submit']))
{
$name = $_POST["name"] ?? "";
if (empty($name)) {
$nameErr = "Name is required";
} else {
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if ($nameErr === "") {
$name = "Seller Name: ".$_POST['name']."";
$phoneno = "Phone Number: ".$_POST['phoneno']."";
$email = "E-Mail: ".$_POST['email']."";
$file=fopen("testing.txt", "a");
fwrite($file, $name);
fwrite($file, $phoneno);
fwrite($file, $email);
fclose($file);
}
}
Also note that there is no checks for other field (phoneno and email), so if they are not set, you will have error!
I created the fields that has validation process like required fields, numbers only and valid email.
it displays the errors simultaneously after submit but upon changing only one of the fields, it accepts and does not revalidate the other.
example
name = Error : required field
telephone = Error : numbers only
email = Error : not a valid email
after i corrected only the email , it accepts and proceed on submitting without rechecking the others.
please see my code . thanks in advance
<?php
include("conn/db.php");
function renderForm($name ='', $tel = '', $email ='', $error='', $error2='', $error3='')
{
?>
<html >
<head> <title>Form</title></head>
<body>
<?php
if ($error != '') {
echo $error
}
if ($error2 != '') {
echo $error2;
}
if ($error3 != '') {
echo $error3;
}
?>
<form action="" method="post">
Name : <input type = "text" class = "form-control" name = "name_text" value="<?php echo $name; ?>"> <br/>
Tel :<input type = "text" class = "form-control" name = "tel_text" value="<?php echo $tel; ?>"> <br/>
Email :<input type ="text" class = "form-control " name = "email_text" value="<?php echo $email; ?>" > <br/>
<input name= "submit" type="submit" value="Update" class = "btn btn-primary" >
</form>
</body>
</html>
<?php
}
if (isset($_POST['submit'])){
$name = $_POST['name_text'];
$tel = $_POST['tel_text'];
$email = $_POST['email_text'];
if ($name== '' ){
$error = 'ERR: required field';
}
if(!is_numeric($telephone)){
$error2 = 'ERR: numbers only';
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
}
else
{
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
renderForm($name, $tel , $email ,$error, $error2, $error3);
}
else{
renderForm();
}
$con->close();
?>
<?php
include("conn/db.php");
function renderForm($name ='', $tel = '', $email ='', $error='', $error2='', $error3='')
{
?>
<html >
<head> <title>Form</title></head>
<body>
<?php
if ($error != '') {
echo $error
}
if ($error2 != '') {
echo $error2;
}
if ($error3 != '') {
echo $error3;
}
?>
<form action="" method="post">
Name : <input type = "text" class = "form-control" name = "name_text" value="<?php echo $name; ?>"> <br/>
Tel :<input type = "text" class = "form-control" name = "tel_text" value="<?php echo $tel; ?>"> <br/>
Email :<input type ="text" class = "form-control " name = "email_text" value="<?php echo $email; ?>" > <br/>
<input name= "submit" type="submit" value="Update" class = "btn btn-primary" >
</form>
</body>
</html>
<?php
}
if (isset($_POST['submit'])){
$name = $_POST['name_text'];
$tel = $_POST['tel_text'];
$email = $_POST['email_text'];
$is_valid = true;
if ($name== '' ){
$error = 'ERR: required field';
$is_valid = false;
}
if(!is_numeric($telephone)){
$error2 = 'ERR: numbers only';
$is_valid = false;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
$is_valid = false;
}
if($is_valid) {
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
renderForm($name, $tel , $email ,$error, $error2, $error3);
}
else{
renderForm();
}
$con->close();
?>
Its just a small mistake:
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
} else {
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
You only checked the email and if it is corecct it was proceding. It did not include the other 2 checks for name and number.
I added a small variable to check if all 3 are correct.
I'm using this code from W3 (http://www.w3schools.com/php/php_form_complete.asp) to make server side validation for given example form.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_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["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["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Although server side validation works fine,I can't put mail() function to work ONLY WHEN both $name (treated as subject) and $comment (treated as message) fields are filled.
I've tried many combinations but email is always submitted even when fields are empty.
So my question is: how to make this validated form send email only when $name and $comment fields are filled and validated?
As you are creating $nameErr when the name is invalid and $comment is an empty string when the comment is valid you can use the following conditional:
if (!$nameErr && $comment) {
}
Empty strings are considered FALSE:
http://php.net/manual/en/language.types.boolean.php
You can always use flags.
<?php
....
// let's say there are some flags for validation
if($flag1 && $flag2 && .. $flagN){
// perform email sending here
}
?>
Or you can use the default error message variables; check if they are empty
<?php
if(!empty($nameErr) && !empty($comment)){
// perform email sending
}
?>
Do the validation after you validated $name and $comment:
if($nameErr == "" && $emailErr == "") { // If they are empty, no errors where found
// Do your email validation here
}
I'm new to PHP so please be gentle!
I'm trying to build a simple PHP form validation with an error message/confirm message. When I submit the form, it's supposed to check if fields are empty and display the corresponding message. But it keeps giving me an error and I have no idea why:
Parse error: syntax error, unexpected T_IF in process.php on line 6
Here's process.php code:
<form action="process.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="submitted" value="1">
<input type="submit">
</form>
<?php
//If form was submitted
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST[fname]){
$fname = $_POST[fname]; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST[lname]){
$lname = $_POST[lname]; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST[email]){
$email = $_POST[email]; //If email was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & email";
}else{
$errormsg = "Please enter email";
}
}
}
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
//If all fields present
if ($fname && $lname && $email){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>
You forgot to add " on post array that is the reason for your error $_POST[lname] change to $_POST['lname']; . Pass string to your $_POST[];
if ($_POST["fname"]){
$fname = $_POST[fname]; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST["lname"]){
$lname = $_POST[lname]; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST["email"]){
$email = $_POST["email"]; //If email was entered
}
Some of your $_POST variables were missing single quotation marks, which is probably what caused the errors. However, generally speaking, there are other code suggestions which I've layed out.
I restructured your code to be more scalable and follow better practice with the following enhancements:
Form values will remember their previous value and not erased on each post.
Removed the 'submitted' field and replaced with if (!empty($_POST)) {} to make sure form was posted.
Moved error messages into an array. This is more maintainable and readable to my taste (imagine having 15+ fields to test for).
Added validate() function to run on your validation tests.
Removed variable assignments ($fname = $_POST['fname']) since they were not used except for the validation, which can access them directly.
Moved all tests inside the main if statement.
Hope this helps!
<form action="process.php" method="post">
First Name: <input type="text" name="fname" value="<?php echo isset($_POST['fname']) ? $_POST['fname'] : ''?>"><br>
Last Name: <input type="text" name="lname" value="<?php echo isset($_POST['lname']) ? $_POST['lname'] : ''?>"><br>
E-mail: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''?>"><br>
<input type="submit">
</form>
<?php
//If form was submitted
if (!empty($_POST)) {
$errors = array();
if (empty($_POST['fname'])){
$errors[] = 'First name must be entered.';
}
if (empty($_POST['lname'])){
$errors[] = 'Last name must be entered.';
}
if (empty($_POST['email'])){
$errors[] = 'Email address must be entered.';
}
if ($errors){ //If any errors display them
$error_msg = implode('<br>',$errors);
echo "<div class=\"box red\">$error_msg</div>";
}
//If all fields present
elseif (validate()){
//Do something
echo "<div class=\"box green\">Form completed and validated!</div>";
}
}
function validate() {
/*you can run all your validation methods here, such as check for length, regexp email verification, etc.*/
$validated = false;
if ($_POST['fname'] && $_POST['lname'] && $_POST['email']) {
$validated = true;
}
return $validated;
}
?>
For the $_POST variables use syntax as $_POST['your variable name']
I corrected your code as below:
<form action="test.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="submitted" value="1">
<input type="submit">
</form>
<?php
//If form was submitted
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST['fname']){
$fname = $_POST['fname']; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST['lname']){
$lname = $_POST['lname']; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST['email']){
$email = $_POST['email']; //If email was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & email";
}else{
$errormsg = "Please enter email";
}
}
}
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
//If all fields present
if ($fname && $lname && $email){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>
As Ohgodwhy said,
You need to change every existence of $_POST[word] to $_POST['word']. Note the '.
And why are you using <input type="hidden" name="submitted" value="1">, this is not a good practice. Better use.
if($_SERVER['REQUEST_METHOD'] == "POST")
The issue here is a lack of register globals being enabled (which is a good thing in my eyes) and not using proper string encapsulation.
You need to change every existence of $_POST[word] to $_POST['word']. Note the '.
I am Using thing type of simple validation. Here is my javascript code:
var ck_name = /^[A-Za-z0-9 ]{3,50}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var ck_mob = /^[0-9 ]{8,11}$/;
function validate(form){
var name = form.name.value;
var email = form.email.value;
var mob = form.mob.value;
var errors = [];
if (!ck_name.test(name))
{
errors[errors.length] = "Your valid Name .";
}
if (!ck_email.test(email))
{
errors[errors.length] = "Your must enter a valid email address.";
}
if (!ck_mob.test(mob))
{
errors[errors.length] = "Your valid Mobile Number.";
}
if (errors.length > 0)
{
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors)
{
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++)
{
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
i am a newbie in this php. i am trying to make some validation for my form which will show the error msg if it exploits my validation rules.
my connection file.
<?php
$con = mysql_connect("localhost","root","") or die('could not connect the server: '. mysql_error());
mysql_select_db("interview",$con);
?>
my validate.php file
<?php
require_once('connect.php');
$realnameErr = $nickErr = $passwordErr = $emailErr = "";
$realname = $nick = $password = $email = "";
?>
my form
<form name='v2' id='login' method='post' action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Login</legend>
<label for='realname' >Real Name*:</label>
<input type='text' name='realname' id='realname' maxlength="50" value="<?php echo $realname;?>" /></br>
<span class="error"><?php echo $realnameErr;?></span>
<br>
<label for='nick' >Nick*:</label>
<input type='text' name='nick' id='nick' maxlength="50" value="<?php echo $nick;?>" /></br>
<span class="error"><?php echo $nickErr;?></span>
<br>
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" /></br>
<span class="error"><?php echo $passwordErr;?></span>
<br>
<label for='email' >Email*:</label>
<input type='text' name='email' id='email' maxlength="50" value="<?php echo $email;?>"/></br>
</fieldset>
<input type='submit' name='submit' value='submit' />
</form>
validation begins here
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['submit'])) {
if (empty($_POST["realname"]))
{
$realnameErr = "Name is required";
}
else
{
$realname=test_input($_POST["realname"]);
if(!preg_match("/^[a-zA-z ]*$/",$realname))
{
$realnameErr = "only letters and white space allowed";
}}
if(empty($_POST["nick"]))
{
$nickErr = "Nick is required";
}
else {
$nick=($_POST["nick"]);
}
if(empty($_POST["password"]))
{
$passwordErr = "password is required";
}
else {
$password=($_POST["password"]);
}
if(empty($_POST["email"]))
{
$emailErr = "email is required";
}
else {
$email=test_input($_POST["email"]);
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}}
checking then inserting
if((!$realnameErr) && (!$nickErr) && (!$passwordErr) && (!$emailErr)) {
$query="INSERT INTO `main`"."(realname,nick,password,email)". "VALUES". "('$realname','$nick',SHA('$password'),'$email')";
$res=mysql_query($query);
echo '<p>Your account has been Successfully created,You are now ready to login. </p>';
}
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
You need to have your working Script before you display your form. Because at the moment, the time you output <span class="error"><?php echo $nickErr;?></span> the variable $nickErr is still empty and therefore does not display anything.
Try this:
// Init
$errors = array();
// Validate Post Data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit'])) {
if (empty($_POST["realname"])) {
$errors[] = "Name is required";
} else {
$realname = test_input($_POST["realname"]);
if (!preg_match("/^[a-zA-z ]*$/", $realname)) {
$errors[] = "only letters and white space allowed";
}
}
if (empty($_POST["nick"])) {
$errors[] = "Nick is required";
} else {
$nick = ($_POST["nick"]);
}
if (empty($_POST["password"])) {
$errors[] = "password is required";
} else {
$password = ($_POST["password"]);
}
if (empty($_POST["email"])) {
$errors[] = "email is required";
} else {
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$errors[] = "Invalid email format";
}
}
}
}
// If there is any error
if (sizeof($errors))
{
// display it
echo '<div>Following error(s) occured:<br /><br />'. implode('<br />', $errors) .'</div>';
}
else
{
// proceed with db insert here
}