I am a new programmer and am attempting to do some validation for a basic registration form. I have built a basic registration form that sends the user back to the same page when submitted. I have also created a user class and have created some basic validation functions. However, the functions have the error messages built into them. I obviously put the functions on the top of the registration form so when there is an error the errors are posted on the registration form. However, I have no control on how the error messages look and would like to know if there is a lot better way to somehow echo the error messages from outside the class so I can use some type of css or something else for better control of how they look. I hope that makes sense. Also when there is an error the user is sent back to an empty registration form. I was trying to figure out how to keep the valid information in the text boxes and just make them redo the invalid information. Here is a basic example of a validation I have done. I know its basic but I am very new to programming
function validate_password($password)
{
$valid = TRUE;
if ($password == '')
{
echo "<p> Please enter a value for the password </p>";
$valid = FALSE;
}
elseif($_POST['pwd'] !== $_POST['pwd2'])
{
echo "The passwords do not match please try again";
$valid = FALSE;
}
return $valid;
}
Don't echo them right away, instead store them for later use. You mentioned this is inside a class, so you can use a class property to hold error messages.
class YourClass
{
public $error;
function validate_password($password)
{
$valid = TRUE;
if ($password == '')
{
// Set the error message
$this->error = "Please enter a value for the password";
$valid = FALSE;
}
// etc...
}
}
Later, when you need to, you can output it in the HTML:
if (!empty($yourclass->error)) {
echo "<p class='errmsg'>{$yourclass->error}</p>\n";
}
You then just need a CSS class errmsg and you can style it how you like:
.errmsg {
color: #FF0000;
font-size: 36px;
}
Now if you have that working, you can expand it further to make the $error class property into an array and push multiple messages onto it:
// In the class, initialize it as an array
$this->error = array();
// Use the [] notation to append messages to the array.
$this->error[] = "Another error message..."
$this->error[] = "And yet another error message..."
In your presentation code, use a loop to output the messages:
// Output a big stack of error messages...
foreach ($yourclass->error as $err) {
echo "<p class='errmsg'>$err</p>\n";
}
What I normally do with classes and their errors is have a variable specifically for the errors.
So something like:
class User
{
private $_ValidationErrors = array();
function validate_password($password)
{
$this->_ValidationErrors = array();
$valid = TRUE;
if ($password == '')
{
$this->_ValidationErrors[] = "Please enter a value for the password";
$valid = FALSE;
}
elseif($_POST['pwd'] !== $_POST['pwd2'])
{
$this->_ValidationErrors[] = "The passwords do not match please try again";
$valid = FALSE;
}
return $valid;
}
function ValidationErrors ()
{
if (count($this->_ValidationErrors) == 0)
return FALSE;
return $this->_ValidationErrors;
}
}
Then to use:
$user = new User();
if (!$user->validate_password('somepass'))
echo implode('<BR>',$user->ValidationErrors ());
EDIT: To display errors by the user something like:
<?php
if (isset($_POST["submit"]))
{
$user = new User();
$passwordErrors = (!$user->validate_password($_POST["pass1"]))?$user->ValidationErrors():array();
}
?>
<form action="<?php echo $_SERVER["php_self"]; ?>" method="post">
<input type="text" name="pass1" value="<?php echo htmlspecialchars($_POST["pass1"]); ?>" /><BR/>
<?php
echo ((isset($passwordErrors) && count($passwordErrors) == 0)?"":implode("<BR/>", $passwordErrors));
?>
<input type="submit" name="submit" value="Register" />
</form>
Related
i am beginner php programmer, iv been trying to create a small program that takes input from a forum and then after submission i want it to be printed on the screen. simple and easy i thought, iv been trying and suspiciously it seems to work fine for 1 text field, when i added the remaining 2 text fields called [fam][user] my code stops returning the content to the screen. also i started to recieve an error of an unindex array, therefore i had to use isset to counter this problem, and also, why does my code call the destructor although i never implicitly set my destructor. i dont know how to ask these questions because the errors arent consistent.
code doesnt print my [name][fam][user]
code prints [name] when everything about [fam][user] are ommited from the code.
-code sometimes called the destructor
-code doesnt clear html previous input(e.g, when working with the one text field, lets say i input the [name] john, and click submit it
displays submit, then,i refresh the page, and the name john is still
displayed, why doesnt the destructor clear the memory of name from my
submission.
<form class="nameform" action="book.php" method="post">
<input type="text" name="Name" value="1">
<input type="text" name="Fam" value="2">
<input type="text" name="User" value="3">
<input type="button" name="submit" value="Submit">
</form>
private $name; private $familyName; private $userName;
function __construct($names,$familyNames,$userNames)
{
$this->name = $names;
$this->familyName = $familyNames;
$this->userName = $userNames;
}
function getName()
{
return $this->name;
}
function getFamilyName()
{
return $this->familyName;
}
function getUserName()
{
return $this->userName;
}
public function __destruct()
{
echo "destroyed again";
$this->name;
$this->familyName;
$this->userName;
}
}
if(!isset( $_POST["Name"])||!isset($_POST["Fam"])||!isset($_POST["User"]))
{
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
// $n = $_POST["Name"];
// $f = $_POST["Fam"];
// $u = $_POST["User"];
// $p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
?>
code doesnt print my [name][fam][user]
You never echo them out of the destuctor
public function __destruct()
{
echo "destroyed again";
$this->name; //<---- does nothing
$this->familyName;
$this->userName;
}
So I am not sure what this is supposed to do. You have them down at the bottom
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
But the only thing you'll get from the destruct method is
"destroyed again"
And you will only see that if everything in the form is set. Which it always is when the form is submitted, because type text is always submitted with its form.
Which brings me to this, you should be checking empty instead of isset there
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
if(empty($_POST["Name"])||empty($_POST["Fam"])||empty($_POST["User"])){
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Note that anything falsy will be empty, false, [], '', 0, '0', null etc.
I don't know if this solves all of you problems, but these things could produce some of the behaviour you are experiencing.
Another more advance way to check these is like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
$post = array_filter( $_POST, function($item){
return strlen($item); //any thing of a length of 0 is removed
});
if(count($post) != count($_POST)){
foreach(array_diff_key( $_POST, $post) as $missing=>$empty) {
echo "Please fill in $missing\n";
}
}else{
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Output
Please fill in Name
Please fill in Fam
You can test it online Here
Cheers!
i have some function for checking password is required and compare it with verification here's my function:
public function required($field= array())
{
foreach($field as $value) {
if (isset($this->_input[$value])) {
if (empty(Security::clean($this->_input[$value]))) {
$messages = "is Required.";
error::inputError($value, $messages);
}
} else{
$messages = "Not Found.";
error::inputError($field, $messages);
}
}
}
public function password($field, $confirmasion){
if (isset($this->_input[$field] , $this->_input[$confirmasion])){
if ($this->_input[$field] != $this->_input[$confirmasion])
{
$messages = "is different with $confirmasion.";
error::inputError($field, $messages);
error::inputError($confirmasion, $messages);
}
}
}
In my class $this->_input refers to $_POST. and then i have a class to set an error like this:
public static function inputError($field, $messages)
{
if (is_array($field)) {
foreach ($field as $key){
$newName = General::changeName($key);
$messagesError = "$newName $messages";
if (isset(self::$_errors[$key])){
return;
}else{
self::$_errors[$key] = $messagesError;
}
}
}else{
$newName = General::changeName($field);
$messagesError = "$newName $messages";
if (isset(self::$_errors[$field])){
return;
}else{
self::$_errors[$field] = $messagesError;
}
}
}
i'm expecting when when i submit form and my password and verification fields is empty it display "password is required" or "verification is required" only without showing error "password is different from verification”. but when i'm only fill my password fields it showing “verification is required“ and the second error "password is different different from verification” because my verification is still empty. Is it something wrong with my logic or something?
isset($this->_input['fieldname'])
this code will return true. Hence, having the verification field empty will still compare it to the password field.here's the solution:
(!empty($this->_input[$field]) && !empty($this->_input[$confirmasion]))
Just trying to find out the best way to get my custom error message working. Isset does not seem to work in codeigniter.
And for some reason my inputs are displaying the number '1'
Controller
<?php
class Step_3 extends MX_Controller {
private $error = array();
public function index() {
if(($this->input->server('REQUEST_METHOD') == 'POST') && $this->validate()) {
$data['db_hostname'] = $this->input->post('db_hostname');
}
if ($this->error['db_hostname']) {
$data['error_db_hostname'] = $this->error['db_hostname'];
} else {
$data['error_db_hostname'] = '';
}
if ($this->input->post('db_hostname')) {
$data['db_hostname'] = $this->input->post('db_hostname');
} else {
$data['db_hostname'] = 'localhost';
}
}
private function validate() {
if (!$this->input->post('db_hostname')) {
$this->error['db_hostname'] = 'Hostname required!';
}
}
} // End Of
On View File Sample
<input type="text" name="db_hostname" value="<?php echo $db_hostname; ?>" id="input-db-hostname" class="form-control" size="50"/>
<?php if ($error_db_hostname) { ?>
<div class="text-danger"><?php echo $error_db_hostname; ?></div>
<?php } ?>
Your "validate" function doesn't return anything, so your first if statement will never be true.
Also at the moment the input will automatically have a value of 'localhost'. It may be better to test for an empty string and strip spaces just in case like this:
if ("" == trim($this->input->post('db_hostname')))
I am trying to create function that takes two arguments one for the user input and the other a message for error. I initially have an associative array with the two input fields and the corresponding error.
When the function is submitted without any entry I get two similar output; I thought I would get 'test1' and 'test2'. I am passing different arguments each time but I get the same result. The code is below
$valid = TRUE;
//$errors='';
$errors=array('desc_error'=>'please enter valid description',
'title_error'=>'provide valid title','no_error'=>'',);
function sanitizeText($input,$error){
//$input;
if($input!='')
{
$input= filter_var($input, FILTER_SANITIZE_STRING);
if($input==''){
global $errors;
$errors[$error];
$valid=FALSE;
return $errors[$error];
}
else{
$input;
echo 'test 1';
return $input;
}
}
else if($input=='')
{
if($input==$_POST['desc'])
{
echo 'the description field is required<br/>';
$valid=FALSE;
}
else{
//
}
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText($_POST['title'],'title_error');
$desc=sanitizeText($_POST['desc'],'desc_error');
}
?>
<form method="post" action="">
<p>Book Title:<input type="text" name="title" maxlength="100" value=""/></p>
<p>Desc:<input type="text" name="desc" maxlength="100" value=""/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
I think you are trying to validate form using php you can also user javascript to validate but to do it using php please refer following links.
http://myphpform.com/required-optional-fields.php
http://coredogs.com/lesson/form-and-php-validation-one-page
http://www.phpf1.com/tutorial/php-form.html?page=3
and
http://www.montanaprogrammer.com/php-web-programming/php-form-validation/
Your code does not make sense logic wise. Firstly, you check if $input is an empty string, or is not, and then within that first check.. you again make the same exact check. Since ifs are evaluated in order, and input is not ever going to be an empty string, the first if will always execute.
Then, your first 'else'; it will only execute if the $input variable is an empty string.. I can sort of see what you're attempting to do, but it won't work as it is right now. In order for it to work, it would have to look something like the below:
function sanitizeText($input,$error) {
global $errors;
global $valid;
$input_val = filter_var($_POST[$input], FILTER_SANITIZE_STRING);
if ($input_val != '') {
$valid = TRUE;
return $input;
}
else if ($input_val == '') {
$valid = FALSE;
echo $errors[$error].'<br />';
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText('title','title_error');
$desc=sanitizeText('desc','desc_error');
}
If the input value is not an empty string, it will return the input value. If it is, it will not return anything and will instead echo the appropriate error.
I have a contact form and I handle errors by checking each field one-by-one with an "if" statement. I find this hard and I can't seem to find a better/more productive way to get them working. I would also like a heading saying "Error" if one (or more) is true. But I cant get them to work with the separate "if" statements.
Here is my code:
$name = $_POST['name']; //get data from the form
$email = $_POST['email'];//get data from the form
$message = $_POST['message'];//get data from the form
if($name == ""){
echo"<p class='error'>Please enter a name.</p>";
}
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)){
echo "<p class='error'>Your email address is not valid.</p>";
}
if($message == ""){
echo"<p class='error'>Please enter a message.</p>";
}
else{
echo"all ok, send email code...";
}
Edit: These errors are for the validation of the form.
But I cant get them to work with the separate "if" statements.
Just store error in a variable
$error = array();
if($name == ""){
$error[] = "Please enter a name.";
}
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)){
$error[] = "Your email address is not valid.";
}
if($message == ""){
$error[] = "Please enter a message.";
}
if (!$error) {
// do not echo anything here
// but send an email
// and use header("Location:") to redirect a user to thanks page
} else {
echo "Error";
foreach ($error as $line) {
echo "<p class='error'>$line</p>";
}
}
You are looking for validator class. Also see:
Building An Extensible Form Validator Class
The most professional way would be to have each field be an object with a validation method.
Then you can call each field object and ask them to validate themself.
If you would like to go any further (might be overkill though) you put your objects in a list.
Each of these objects are child to an interface with the validation method. So for each object in the list, you call the validation method.
Well, you can't check all fields together as different rules may apply to each one. So what you are doing is fine, except for a mistake you made: The else part should only be echoed, when no error occurred, but in your situation the else only applies to the last if. So even if the validation of name and email fails, as long as the message one does not, the final action is done.
You could easily add some $has_error variable that contains true as soon as an error was found. Or you could use an array that holds all error messages like this:
$errors = array();
if ( empty( $name ) )
$errors[] = 'Please enter a name.';
if ( !eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email ) )
$errors[] ='Your email address is not valid.';
if ( empty( $message ) )
$errors[] = 'Please enter a message.';
// individual checks done
if ( sizeof( $errors ) > 0 )
{
echo '<p class="error"><strong>Errors found:</strong><br />';
echo implode( '<br />', $errors );
echo '</p>';
}
else
{
echo 'No error, everything is fine.';
}
First, don't use ereg*() functions for regular expressions matching, these are deprecated and slow. Use the preg_*() functions instead.
Also take a look at PHP's filter extension.
It provides functions to check and validate various data which you can use directly or incorporate into your own validator functions.
EDIT: Example for checking an e-mail address (see also examples on php.net):
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
echo 'Invalid e-mail "'.$email.'"';
Speaking of validation in an object-oriented manner, you could have a generic validator class with basic validation functions (where you could also integrate filter functions for a consistent API).
Additionally, if your data logically belongs together such that you can group them into objects and manage them as such, implement a validate() method in the classes of these objects that checks the object's properties by utilizing the filter functions and/or your validator class.
class Message {
private $name;
private $email;
private $text;
...
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getEMail() {
return $this->email;
}
public function setEMail($email) {
$this->email = $email;
}
...
public function validate() {
$errors = array();
$nameLength = strlen($this->name);
if ( ($nameLength === 0) or ($nameLength > self::NAME_MAX_LENGTH) )
$errors['name'] = 'Name must be between 1 and '.self::NAME_MAX_LENGTH.' characters.';
if ( !Validator::isEMail($this->email) )
$errors['email'] = 'Invalid e-mail "'.$this->email.'"';
// Other checks
...
// Return TRUE if successful, otherwise array of errors
return ( count($errors) === 0 ? true : $errors );
}
}
Then, you could load all your form inputs into your object like this:
$message = new Message();
$message->setName($_POST['name']);
$message->setEMail($_POST['email']);
$message->setText($_POST['text']);
...
$result = $message->validate();
if ( $result === true ) {
// Success
} else {
// Error
foreach ($result as $validationError) {
// Print error
echo htmlentities($validationError).'<br />';
}
}