I think this is very simple but I don't know how to execute it.
I have a form with some data and I have created a another php file to validate the form data, but I am unable to display the error message back into the form if validation fails. I have attached both files, but I don't know hot to execute it :(
My form.php looks like
<form name="form1" method="post" action="process/process_add_page.php">
<fieldset>
<legend>Add Page</legend>
<table width="1056" height="365" border="1">
<tr>
<th width="77" scope="col">Page Title</th>
<th width="962" scope="col"><label for="page_title"></label>
<input type="text" name="page_title" id="page_title"><span style="color:#FF0000">* <?php echo $titleerror;?></span></th>
</tr>
<tr>
<th scope="row">Page Description</th>
<td><label for="page_description"></label>
<textarea name="page_description" class="ckeditor" id="page_description" cols="100" rows="5"></textarea></td>
</tr>
<tr>
<th scope="row">Seo Title</th>
<td><label for="seo_title"></label>
<input type="text" name="seo_title" id="seo_title"></td>
</tr>
<tr>
<th scope="row">Seo Description</th>
<td><label for="seo_description"></label>
<textarea name="seo_description" class="ckeditor" id="seo_description" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<th scope="row">Page Order</th>
<td><label for="page_order"></label>
<input type="text" name="page_order" id="page_order"></td>
</tr>
<tr>
<th scope="row">Page Status</th>
<td><label for="page_status"></label>
<select name="page_status" id="page_status">
<option value="1">Active</option>
<option value="0">Inactive</option>
</select></td>
</tr>
<tr>
<th colspan="2" scope="row"><input type="submit" name="btnsubmit" id="btnsubmit" value="Submit"></th>
</tr>
</table>
<p> </p>
</fieldset>
</form>
and my process_add_pages.php looks like this
<?php
require_once('../../classes/database.php');
require_once('../../classes/pages.php');
require_once('../../classes/redirect.php');
$objPage=new Page();
$titleerror='';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['page_title'])){
$titleerror = "Title is required";
echo $titleerror;
}else
{
$page_title=mysqli_real_escape_string($objPage->conxn,$_POST['page_title']);
if (!preg_match("/^[a-zA-Z ]*$/",$page_title)) {
$titleerror = "Only letters and white space allowed";
}
}
$page_description=mysqli_real_escape_string($objPage- >conxn,$_POST['page_description']);
$seo_title=mysqli_real_escape_string($objPage->conxn,$_POST['seo_title']);
$seo_description=mysqli_real_escape_string($objPage->conxn,$_POST['seo_description']);
$page_order=mysqli_real_escape_string($objPage->conxn,$_POST['page_order']);
$page_status=mysqli_real_escape_string($objPage->conxn,$_POST['page_status']);
}
$objPage->setPage_title($page_title);
$objPage->setPage_description($page_description);
$objPage->setSeo_title($seo_title);
$objPage->setSeo_description($seo_description);
$objPage->setPage_status($page_status);
if($objPage->addPage()){
new Redirect('../index.php?page=page&action=view&success=The page has been created');
}else{
new Redirect('../index.php?page=page&action=view&error=The page could not be created');
}
?>
There are few little changes you have to do to make it work..
There is a couple of problem in your process_add_pages.php file. your code is ..
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['page_title'])){
$titleerror = "Title is required";
echo $titleerror; /*error part-1 */
}else
{
$page_title=mysqli_real_escape_string($objPage->conxn,$_POST['page_title']);
if (!preg_match("/^[a-zA-Z ]*$/",$page_title)) {
$titleerror = "Only letters and white space allowed"; /*error part-2 */
}
}
$page_description=mysqli_real_escape_string($objPage- >conxn,$_POST['page_description']);
$seo_title=mysqli_real_escape_string($objPage->conxn,$_POST['seo_title']);
$seo_description=mysqli_real_escape_string($objPage->conxn,$_POST['seo_description']);
$page_order=mysqli_real_escape_string($objPage->conxn,$_POST['page_order']);
$page_status=mysqli_real_escape_string($objPage->conxn,$_POST['page_status']);
}
if anything goes wrong in the validation it will echo the error message in the process_add_pages.php file. but it will also execute the sql queries. so if there is any problem in validation you can redirect to the form page with an error message.
you can try this new code format...
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['page_title'])){
$titleerror = "Title is required";
new Redirect('../index.php?error="The page need a page title"');
}elseif
{
$page_title=mysqli_real_escape_string($objPage->conxn,$_POST['page_title']);
if (!preg_match("/^[a-zA-Z ]*$/",$page_title)) {
new Redirect('../index.php?error="Only letters and white space allowed"');
}
}
else {
$page_description=mysqli_real_escape_string($objPage- >conxn,$_POST['page_description']);
$seo_title=mysqli_real_escape_string($objPage->conxn,$_POST['seo_title']);
$seo_description=mysqli_real_escape_string($objPage->conxn,$_POST['seo_description']);
$page_order=mysqli_real_escape_string($objPage->conxn,$_POST['page_order']);
$page_status=mysqli_real_escape_string($objPage->conxn,$_POST['page_status']);
}
}
I Think, this is the better way to Check validation. Add onsubmit in form. Check CheckValidation() function in tag.
<form name="form1" method="post" action="process/process_add_page.php" onsubmit="return CheckValidation()">
<fieldset>
<legend>Add Page</legend>
<table width="1056" height="365" border="1">
<tr>
<th width="77" scope="col">Page Title</th>
<th width="962" scope="col"><label for="page_title"></label>
<input type="text" name="page_title" id="page_title">
<span style="color:#FF0000" style="display:none" id="RequiredTitle">* Title is required</span>
<span style="color:#FF0000" style="display:none" id="OnlyLetters">* Only letters and white space allowed</span>
</th>
</tr>
<tr>
<th scope="row">Page Description</th>
<td><label for="page_description"></label>
<textarea name="page_description" class="ckeditor" id="page_description" cols="100" rows="5"></textarea></td>
</tr>
.
.
.
//Rest of the code
</form>
<script>
function CheckValidation()
{
var Title=$('#page_title').val();
if(Title=="")
{
$('#RequiredTitle').show();
return false;
}
else
{
if(!preg_match("/^[a-zA-Z ]*$/",Title))
{
$('#OnlyLetters').show();
return false;
}
}
}
</script>
Related
my login form is not getting validate. javascript is not working. please help me out. I am not getting any alerts.Do Tell me what is wrong with script.
<script type="text/javascript">
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.npassword.value == "") {
alert("Error: Username cannot be blank!");
form.npassword.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.npassword.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.npassword.focus();
return false;
}
alert("You entered a valid password: " + form.npassword.value);
return true;
}
</script>
this is login form
<div class="section section_with_padding" id="contact">
<h2>Change Password</h2>
<div class="half left">
<h4> </h4>
<table width="91%" align='center' cellpadding= "0" cellspacing= "0" class='main_tab'>
<tr>
<td class='login_table' align='left'><form action="changepass.php" method="post" onsubmit="return checkForm(this);>
<table class="login_tab">
<td class='login_table' align='left'><form method='post'>
<tr>
<td colspan="2" class='login_nam' valign='middle'>Change Password</td>
</tr>
<tr>
<td class='login style1'>Username:</td>
<td class='login'><input type='text' name='username'> </td>
</tr>
<tr>
<td class='login style1'>Old Password:</td>
<td class='login'><input type='password' name='opassword'> </td>
</tr>
<tr>
<td class='login style1'>New Password:</td>
<td class='login'><input type='password' name='npassword'> </td>
</tr>
<tr>
<td class='login' colspan='2'><input type='submit' name='submit' value='Change'>
</td>
</tr>
</table>
</form> </td>
</tr>
</table>
</div>
</div>
please some one help in validating the login page with errors on not providing any input(it should display respective error message).
Looks like you have created a nested form. Please delete the second one.
<form action="changepass.php" method="post" onsubmit="return checkForm(this);> /* Form HTML */
<td class='login_table' align='left'>
<form method='post'> /* Remove this */
Hope this helps.
Peace! xD
I'm trying to allow users to change their passwords in my site.
I'm getting stuck in the controller. My doubt is whether $sql = $this->db->select("*")->from("logins_table")->where('lt_username',$this->session->userdata('email'))->get(); is working or not.
My controller:
<?php
class Changepw extends MY_Controller {
public function Changepwd(){
}
public function reset() // we will load models here to check with database
{
$sql = $this->db->select("*")->from("logins_table")->where('lt_username',$this->session->userdata('email'))->get();
foreach ($sql->result() as $my_info) {
$db_password = $my_info->lt_password;
$db_id = $my_info->lt_id;
}
if($this->input->post('opassword') == $db_password && ($this->input->post('npassword') != '') && ($this->input->post('cpassword')!='')) {
$fixed_pw = mysql_real_escape_string(md5($this->input->post('npassword')));
$update = $this->db->query("Update 'logins_table' SET 'lt_password'= '$fixed_pw' WHERE 'id'= '$db_id'")or die(mysql_error());
//$this->form_validation->set_message('change',"sucess");
echo json_encode(array("success"=>true));
}else {
//$this->form_validation->set_message('change', "err");
echo json_encode(array("success"=>false));
}
exit;
}
}
and my view page is:
<table width="95%" border="0" cellspacing="5" cellpadding="5">
</tbody>
<tr>
<td width="35%" class="heading">Email</td>
<td><input type="text" name="email" ></td>
<tr>
<td class="heading">Existing Password</td>
<td><input type="password" name="opassword" ></td>
</tr>
<tr title="Ignore new password if you dont want to change password">
<td class="heading">New Password</td>
<td><input type="password" name="npassword"></td>
</tr>
<tr>
<td class="heading">Confirm Password</td>
<td><input type="password" name="cpassword"></td>
</tr>
<tr>
<td> </td>
<td><button name="Submit" id="forgotBtn" class="customBtn" value="Submit">Save changes</button>
</td>
<tr>
<td> </td>
<td ><div class="errorMsg" id="errMsg" style="display:none"> Error in updating </div></td>
</tr>
</tr>
</tbody>
</table>
</form>
$("#forgotBtn").on('click', function()
{
$.post( "/changepw/reset", $("#forgotForm").serialize(), // serializes the form's elements.
function(data) {
data = jQuery.parseJSON(data);
if(data.error == false) {
$("#successMsg").hide();
}else{
$("#errMsg").show();
}
} );
return false;
});
Thanks.
I think according to the code, your error is here.
$this->input->post('opassword') == $db_password// this line
While storing password in database you have used md5(), but here you are just checking for the plain text which is wrong
md5($this->input->post('opassword')) == $db_password
This should help you.
I know how to validate a form in JavaScript, but not in php.
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Cafeteria Ordering System</title>
<style type="text/css">
#import "cafeteriastyle.css";
</style>
</head>
<body>
<?php
if(isset($_POST['btnSubmit']))
{
//2nd page
}
else
{
?>
<form name="form1" method="post">
<table width="500" border="0" align="center" class="TableBorder">
<tbody>
<tr>
<td colspan="2" align="center" class="TableTitle TableHeadingFill">Cafeteria Ordering System</td>
</tr>
<tr>
<td width="250" align="right"><p>Customer ID</p></td>
<td><input type="text" name="txtID"></td>
</tr>
<tr>
<td align="right"><p>Num. Of Items Order</p></td>
<td><input type="text" name="txtItems"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btnSubmit"></td>
</tr>
</tbody>
</table>
</form>
<?php
}
?>
</body>
</html>
I have a form call "form1", inside the form1, I have 2 textfield.
When the Submit button is clicked, I want to perform a form validation check, to make sure the both textfield is filled, and jump to the 2nd page. If textfield is empty, display a alert message and stay on the same page.
I know how to do it with JavaScript, for example:
<script language="javascript" type="text/javascript">
function formValidation()
{
if(form1.elements["Name"].value.trim() == "")
{
alert("Please enter the name");
form1.elements["Name"].select();
return false;
}
return true;
}
</script>
and just need to add onSubmit="return formValidation" into the form tag like:
<form name="form1" method="post" onSubmit="return formValidation()"> then it will working probably. But how to do that with php instead of JS?
<?php
if(isset($_POST['btnSubmit']))
{
$txnid=trim($_POST['txtID']);
$txtItems=trim($_POST['txtItems']);
if(!empty($txnid) && !empty($txtItems))
{
//2nd page
}
else
{
echo 'Both Fields are Required.';
}
}
else
{
?>
<form name="form1" method="post">
<table width="500" border="0" align="center" class="TableBorder">
<tbody>
<tr>
<td colspan="2" align="center" class="TableTitle TableHeadingFill">Cafeteria Ordering System</td>
</tr>
<tr>
<td width="250" align="right"><p>Customer ID</p></td>
<td><input type="text" name="txtID"></td>
</tr>
<tr>
<td align="right"><p>Num. Of Items Order</p></td>
<td><input type="text" name="txtItems"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btnSubmit"></td>
</tr>
</tbody>
Use zebra form http://stefangabos.ro/php-libraries/zebra-form/
it is the best
will do both php and js validation
Use this check with jquery it might be help you
function formValidation()
{
if($("input[name='name']").trim() == "")
{
alert("Please enter the name");
$("input[name='name']").focus();
return false;
}
return true;
}
Try this...
function formValidation()
{
if($("input[name='name']").val().trim() == "")
{
alert("Please Enter The Name");
return false;
}
return true;
}
got a question, that I can't find a solution for. Before I continue with my question, just a brief overview of what the code is suppose to do (This is for a class project in a beginning php course). User automatically starts on the index.php page. Once the quantities are inputed, it will take them to the login.php page. If they have a login, then it will take them to the invoice.php page. If not, then it will take them to the register.php page, then go to the invoice.php page.
Here's where I run into a problem, how do I match the username and password (inputed from the user registration page) from my user.dat file to the login page? It's frustrating because we really didn't go over it in class :(
Any help will be greatly appreciated, feel free to give feed back on any of the code presented :)
Thank you so much in advance folks! This site has definitely ease some of the coding headaches :P
login.php
<h3>
<center>
Please Login
</center>
</h3>
<?php
include "functions.inc";
//if the form data is clicked... if all valid.. display invoice... otherwise display error
$datafile = "users.dat";
$file = file_get_contents($datafile);
if(!strpos($file, "search string")) {
echo "String not found!";
}
if (array_key_exists('submit', $_POST))
{
if(!strpos($file, "search string")) {
echo "String not found!";
}
header('Location: registration.php');
}
else
if (array_key_exists('register', $_POST))
{
header('Location: invoice.php');
}
?>
<?php//made the user login menu into a nice table that will center the username and password in the middle of the page.?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<form name="form1" method="post" action="invoice.php">
<tr>
<td>Username</td>
<td>:</td>';
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</table>
<center><input type='submit' name='submit' value='Login'></center>
</form>
<?php
/*This code will allow a new user to go to the registration page and register for the site
* before buying anything.
*/
?>
<br>
<form name="form1" method="post" action="registration.php">
<center><input type='submit' name='Register' value='New User? Click here.'></center>
</form>
registration.php
<html>
<h4>
<center>
New User Registration
</center>
</h4>
<body>
<?php
/*
* What this code does, is it takes the users registration information, and stores it in a file.
* After that what I hope to do is to retrive the same file when the user is on the login page and if
* the login matches whats in the file, then proceed to the invoice page.
*/
include "functions.inc";
// Define the datafile to hold the $users array
$datafile = "users.dat";
// See if the user has submitted something
if (array_key_exists('register', $_POST))
{
// Get the new user info
$the_user = $_POST['newUser'];
// Load the file of users and store it in $users
$users = arrayfile_to_array($datafile);
// Validate user name and password
if (user_exists($the_user['ID'], $users))
{
echo "<p><center>Please fill in all text boxes</center></p>";
}
else
{
// If valid, save to the file of users
$users[] = $the_user;
array_to_arrayfile($users, $datafile);
}
}
else
{
if (!file_exists($datafile)) // Data file doesn't exist, so create it
{
$users = array();
array_to_arrayfile($users, $datafile);
}
}
?>
<?php
// my defined error values
$errEmail = "";
$errUser = "";
$errPass = "";
if(isset($_POST["register"])){
// User must be digits and letters
if(preg_match("/^[0-9a-zA-Z]{5,}$/", $_POST['newUser']['ID']) === 0)
$errUser = '<span class="error">Username must be more than 5 characters and contain letters and numbers.</span>';
// Password must be strong
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST['newUser']['password']) === 0)
$errPass = '<span class="error">Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit</span>';
//Email validation
if(preg_match("/^[a-zA-Z]\w+(\.\w+)*\#\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST['newUser']['email']) === 0)
$errEmail = '<span class="error">example: chars(.chars)#chars(.chars).chars(2-4)</span>';
}
?>
<form action = "<?= $_SERVER['PHP_SELF'] ?>" method= 'POST'>
<center>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td>Username</td>
<td>:</td>
<td ><input name="newUser[ID]" type="text" size="16" value="">
<?php if(isset($errUser) and $errUser !='') echo $errUser; ?>
</td >
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="newUser[password]" type="password" size="16" value="">
<?php if(isset($errPass) and $errPass !='') echo $errPass; ?>
</td >
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="newUser[email]" type="text" size="50" value="">
<?php if(isset($errEmail) and $errEmail !='') echo $errEmail; ?>
</td >
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<input type='submit' name='register' value='Register'>
</center>
</form>
</body>
</html>
I am not able to place this astrik(*) after the text box in my code.Secondly,My form is displaying towards down.I am not able to figure out the problem.Could you please help me out.Please try to give more explanation as soon as possible.
<style>
.error {color: #FF0000;}
</style>
<?php
$firstnameErr = $lastnameErr = $emailErr = "";
$firstname = $lastname = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["firstname"]))
{$firstnameErr = "Name is required";}
else
{
$firstname = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"]))
{$lastnameErr = "Name is required";}
else
{
$lastname = test_input($_POST["lastname"]);
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div text align =center><h1>Eventous Info</h1></div>
<h3>Fill the Required Form:</h3>
<p><span class="error">*required field</span></p>
<table>
<form action="insert.php" method="post">
<tr>
<td>Firstname</td><td>:</td> <td><input type="text" name="firstname" >
</td>
<span class="error">* <?php echo $firstnameErr;?></span><br><br>
</tr>
<tr>
<td>Lastname</td><td>:</td><td><input type="text" name="lastname" ></td>
<span class="error">* <?php echo $lastnameErr;?></span><br><br>
</tr>
<tr>
<td>Email</td><td>:</td><td><input type="text" name="email"></td>
<span class="error">* <?php echo $emailErr;?></span><br><br>
</tr>
<tr>
<td>Phone</td><td>:</td><td><input type="text" name="number"><td><br><br>
</tr>
</table>
<input type="submit" >
</form>`
The <span> element with the asterisk needs to be inside a table cell (td). If you want it in the next cell over, wrap it in another <td> tag; if you want it in the field with the input, put it immediately after the input and before </td>
The way you are wrapping the colon in it's own cell makes me wonder if you're setting the table up correctly also. I would look at keeping the table to three cells per row:
<tr>
<td>Firstname:</td>
<td><input type="text" name="firstname" /></td>
<td><span class="error">* <?php echo $firstnameErr;?></span></td>
</tr>
You have to put the <span class="error">* <?php echo $firstnameErr;?></span> inside a table cell , like <td>my content</td>. Objects are not allowed outside cells in tables.
Also, table cells are only allowed inside rows. The structure of tables should be like this:
<table>
<tr>
<td>Row 1 Cell A</td>
<td>Row 1 Cell B</td>
<td>Row 1 Cell C</td>
</tr>
<tr>
<td>Row 2 Cell A</td>
<td>Row 2 Cell B</td>
<td>Row 2 Cell C</td>
</tr>
</table>
If you place objects anywhere else inside a table, the browsers don't know where to put them. Usually the objects are just put right above or below the table.