PHP Empty and data validation - php

When a user submit forms,i'm checking empty validation and data validation.
For ex:In data ,first field is name,i'll check whether user has entered any other characters else than alpha character's.if he has entered then will show him an error message.Name should contain minimum of 4 characters and max of 20 characters
I'm using this code but it is not working correctly.How to check the regex.
$validate = array("Category"=>"$productCategory", "Name" => "$productName");
$error = '';
foreach ($validate as $key => $field) {
if (preg_match('/^[a-z\d ]{4,20}$/i', $$field)) {
echo $error .= $field;
}
}
Thanks in advance!

You have a typo in the preg_match, you type $$field (2x$) instead of $field, your regex is fine it will match:
- a character between a - z (case insensitive)
or
- a digit between 0 - 9
or
- a "space" character.
Update code to answer #Andrius Naruševičius comment
$validate = array("Category" => $productCategory, "Name" => $productName);
$error = '';
foreach ($validate as $key => $field)
{
if (preg_match('/^[a-z\d ]{4,20}$/i',$field))
{
$error.= $field;
}
}
if($error)
{
echo $error;
exit;
}

Do you mean:
$validate = array("Category"=>$productCategory, "Name" => $productName);
foreach ($validate as $key => $field) {
if (preg_match('/^[\w\d]{4,20}$/i',$field)) {
echo $error .= $field;
}
}

Related

Function to Check if POST is empty and add custom error messages

I have some code to check an empty post like this:
foreach($_POST as $key => $value)
{
if (empty($_POST[$key]))
{
$errors[] = "$key" . "is empty.";
}
}
how can i add some custom messages because using $key + is empty isn't good enough for me. i want to display custom messages for every post. maybe some function like validate($name, Please enter your name, required). but i don't have a clue how to do it, can anyone can provide me some method i can try?
Since you want a custom message depending on the key, you should just use a switch.
$errors = array();
foreach($_POST as $key => $value)
{
if (empty($value))
{
switch($key) {
case 'name':
$errors[] = "The name is empty.";
break;
case 'age':
$errors[] = "The age is empty.";
break;
default:
$errors[] = $key . " is empty.";
}
}
}
* Edit *
If you want to do special treatment according to the key, and use a function :
$errors = array();
foreach($_POST as $key => $value)
{
$result = validate($key, $value);
if (!empty($result)) {
$errors[] = $result;
}
}
function validate($key, $value) {
if ($key == 'name' && empty($value)) {
return 'You must enter your name';
}
elseif ($key == 'age' && empty($value)) {
return 'You must enter your date of birth';
}
elseif ($key == 'email' && filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
return 'Your email is incorrect';
}
return '';
}
Check for Form Validation scripts/tutorials with PHP.
Here are some quick findings:
Using modular approach: http://www.sitepoint.com/form-validation-with-php/
Using class based (OOP) approach: http://www.html-form-guide.com/php-form/php-form-validation.html
if you want to use same approach, then use this
foreach($_POST as $key => $value)
{
if (empty($_POST[$key]))
{
$errors[] = getValidationMessage($key);
}
}
function getValidationMessage($key){
if($key == "user_name")
return "please enter user name.";
else if ($key == "date_of_birth")
return "please enter you date of birth";
//and so on,
//based on param names in your html-forms
}
Something like this?
foreach ($_POST as $k => $v) {
$errors[] = validate($k);
}
function validate($key) {
if(empty($_POST[$key])) {
switch ($key) {
case 'name':
$message = "Name is empty";
break;
case 'email':
$message = "fill in your email address";
break;
default:
$message = $key." is empty";
break;
}
return $message;
}
return false;
}

PHP - Echo an array value from a class

I have the following PHP code
<?php
class SimpleEmailServiceMessage
{
public function properNames($formValue) {
$formValue = strtolower($formValue); //Make all letters small case
$formValue = ucwords($formValue); //Make all first letters capital
$formValue = str_replace('','',$formValue); //Remove extra spaces
if(is_numeric($username)) {
$error[] = 'The name is invalid';
}
return $error;
return $formValue;
}
}
$username = 'john doe';
$m = new SimpleEmailServiceMessage();
echo $m->properNames($username);
foreach($error as $result) {
echo $result . '<br>';
}
?>
I am managing to output $username, but I am not managing to output $error[] if it is a number. $error[] in my case is an array as different classes will have an error.
The current code is telling me Array Warning: Invalid argument supplied for foreach() in /web/com/140895582016925/main.php on line 22 which is for foreach($error as $result) {
The error message say it all: your $error is NOT an array.
Take a look at the is_numeric() validation part of your code.
You have an error there.
is_numeric() needs an argument.
In your case i think you need to:
if ( is_numeric($formValue ) )
{
// execute if condition
}
try this
<?php
class SimpleEmailServiceMessage
{
public $error;
public function properNames($formValue) {
$formValue = strtolower($formValue); //Make all letters small case
$formValue = ucwords($formValue); //Make all first letters capital
$formValue = str_replace('','',$formValue); //Remove extra spaces
if(is_numeric($formValue)) {
$this->error[] = 'The name is invalid';
}
return $formValue;
}
}
$username = 'john doe';
$m = new SimpleEmailServiceMessage();
echo $m->properNames($username);
if(isset($m->error))
{
foreach($m->error as $result) {
echo $result . '<br>';
}
}
?>
Demo
Try to use assignment:
$error = $m->properNames($username);
instead of echoing:
echo $m->properNames($username);

Header Redirect after form Validation in PHP

I am trying this code as part of form processing:
<?php
if(isset($_POST['senderEmail']))
{
try
{
require '_php/_security/validation.php'; //SEE BELOW
$rules = array(
'senderEmail' => 'validEmail',
'emailTextbox' => 'validTextbox',
);
$validation = new Validation();
if ($validation->validate($_POST, $rules) == TRUE) {
require("_php/database/dbProcessing.php"); //Form Proccessing for database inclusion
}
else {
foreach($validation->emailErrors as $error){
$emailErrors[] = $error;
$_SESSION['$emailErrors'] = $emailErrors;
header('Location:indexmobile.php#emailErrors');
die('ABORT!');
}
}
}
catch (PDOException $e)
{
$error = 'Error adding elements to database: ' . $e->getMessage();
echo "Error: " . $error;
exit();
}
exit();
}
?>
The validation.php where I do my validation has this:
<?php
class Validation {
public $errors = array();
public function validate($data, $rules) {
$valid = TRUE;
foreach ($rules as $fieldname => $rule) {
$callbacks = explode('|', $rule);
foreach ($callbacks as $callback) {
$value = isset($data[$fieldname]) ? $data[$fieldname] : NULL;
if ($this->$callback($value, $fieldname) == FALSE) $valid = FALSE;
}
}
return $valid;
}
public function validEmail($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$valid = filter_var($value, FILTER_VALIDATE_EMAIL);
if ($valid == FALSE) $this->emailErrors[] = "The $fieldname needs to be a valid email";
return $valid;
}
}
public function validTextbox($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$whitelist = '/^[a-zA-Z0-9 ,\.\+\\n;:!_\-#]+$/';
$textarea = strip_tags($value);
$textarea = mysql_real_escape_string($textarea);
$valid = preg_match($whitelist, $textarea);
if ($valid == FALSE) $this->errors[] = "The $fieldname contains invalid characters";
return $valid;
}
}
}
Upon using this, Im have issues with the redirect (I think). It seems further that Im having errors in validation. My questions are thus:
Am I doing the header redirect correctly? I've read that " header() must be called before any actual output is sent,.." So is this the reason why this redirect is incorrect? how to make a redirect if i need to show/send something to the redirected page?
function validTextbox always ends up an error that the field is empty. Why so?
Is my entire process of form validation a good way of validating form fields (which i learned from watching an online tutorial)? What is a better way?
Is there something wrong with error reporting in this case?
Thank you for those who replies. I am new to PHP and trying my best to learn the language.
1 - There are several ways to pass on a message to the page you are redirecting to. One is through $_GET like this
$message="Some message for the next page.";
$message=urlencode($message);
header("Location:page.php?message=".$message);
then on page.php
if(!empty($_GET['message']))
{
$_GET['message'];
}
similarly you can also use the session (less secure)
$_SESSION['message']='some other message';
then on page.php
if (!empty($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
2 - I would have to see what you are passing to your validate function. You should do a var_dump of $_POST and add that to your question.
3 - It depends on your criteria. If you are just checking for emptiness its overkill. I don't know what text you need / consider valid, but a regex is a reasonable way of enforcing validation.
4 - See #2.

PHP validation on forms

I've five fields in the form
When a form is submitted and if three fields are not filled,it should validate and show errors on those three fields.
I used to do it using if loops,this will show one error at a time,instead, I want to show all the errors.
I want to check special characters,empty validation,min and max characters on each field.
preg_match('/^[a-z\d ]{3,20}$/i', $category
How to check them all at once using PHP?
Update
$errors = array();
$required = array("Name", "Email");
foreach($_POST as $key=>$value)
{
if(!empty($value))
{
$$key = $value;
}
else
{
if(in_array($key, $required))
{
array_push($errors, $key);
}
}
}
This can be used to check empty validation for all fiedls,how do i check for special characters,alpha numeric characters,the provblem would be each field will have different regex.
For eg: phone number and email can not have same regex.
Thanks in advance!
$errors = array();
if (preg_match('/^[a-z\d ]{3,20}$/i', $name)) {
$errors[] = "Please enter valid name.";
}
if (preg_match('/^[a-z\d ]{3,20}$/i', $category)) {
$errors[] = "Please enter valid category.";
}
if (preg_match('/^[a-z\d ]{3,20}$/i', $amount)) {
$errors[] = "Please enter valid amount.";
}
if(!empty($errors))
{
echo "The was an error filling out the form:<br><ul>";
foreach($errors as $msg)
{
echo "<li>$msg</li>";
}
echo "</ul>Please try again.";
}
Or, to make it more concise, use something like Ananth's answer.
// your 3 fields that need to be validated; Key is field, Value is error message if check invalid.
$validate = array("name" => "Please enter valid name.", "category" => "Please enter a real category.", "amount" => "Please enter an amount.");
$error = array();
foreach ($validate as $field => $message) {
if (preg_match('/^[a-z\d ]{3,20}$/i', $$field)) {
$error[] = $message;
}
}
if(!empty($errors))
{
echo "The was an error filling out the form:<br><ul>";
foreach($errors as $msg)
{
echo "<li>$msg</li>";
}
echo "</ul>Please try again.";
}
UPDATE
Seeing as how each check has it's on regex, the first example is easy enough to solve. As for the second example, it only requires a small change.
// your 3 fields that need to be validated;
// Key is Regex, value is array with the variable name (without the $) as the key,
// and the error message as the value.
$validate = array(
'/^[a-z\d ]{3,20}$/i' => array("name" => "Please enter valid name."),
'/^[a-z\d ]{3,20}$/i' => array("category" => "Please enter a real category."),
'/^[a-z\d ]{3,20}$/i' => array("amount" => "Please enter an amount.")
);
$error = array(); // Empty array to store errors in.
foreach ($validate as $regex => $data) { // Key = $regex, Value = array($variable, $error)
if (preg_match($regex, ${$data[0]})) { // This code is untested, so try it without the braces around $data[0]
$error[] = $data[1]; // If the data matches the regular expression provided, add the provided error message to the $error array.
}
}
if(!empty($errors)) // If the $errors array isn't empty (has an error in it)
{
echo "The was an error filling out the form:<br><ul>";
foreach($errors as $msg) // Goes through each error, printing it to an unordered list.
{
echo "<li>$msg</li>";
}
echo "</ul>Please try again.";
}
Note than in the above example, each has the same example regex, but it's simple enough to change those to your needs.
EDIT
All the code above is untested, though it should work, if it doesn't, try removing the braces around $data[0], as mentioned in the accompanying comments.
UPDATE 2
If you need to add an optional checker, the same code can be modified slightly, with an extra foreach loop, for all the optional fields to check.
// your 3 fields that need to be validated;
// Key is Regex, value is array with the variable name (without the $) as the key,
// and the error message as the value.
$required = array(
'/^[a-z\d ]{3,20}$/i' => array("name" => "Please enter valid name."),
'/^[a-z\d ]{3,20}$/i' => array("category" => "Please enter a real category."),
'/^[a-z\d ]{3,20}$/i' => array("amount" => "Please enter an amount.")
);
$optional = array(
'/^[a-z\d ]{3,20}$/i' => array("shipping" => "Please enter valid shipping location."),
'/^[a-z\d ]{3,20}$/i' => array("options" => "Please enter an clean option.")
);
$error = array(); // Empty array to store errors in.
foreach ($required as $regex => $data) { // Key = $regex, Value = array($variable, $error)
if (preg_match($regex, $$data[0])) { // This code is untested, so try it with or without the braces around $data[0]
$error[] = $data[1]; // If the data matches the regular expression provided, add the provided error message to the $error array.
}
}
foreach($optional as $regex => $data)
{
if(strlen(trim($$data[0])) > 0) // If the trimmed length of the string (all leading and trailing whitespace removed) == 0?
{
if (preg_match($regex, $$data[0])) { // This code is untested, so try it with or without the braces around $data[0]
$error[] = $data[1]; // If the data matches the regular expression provided, add the provided error message to the $error array.
}
}
if(!empty($errors)) // If the $errors array isn't empty (has an error in it)
{
echo "The was an error filling out the form:<br><ul>";
foreach($errors as $msg) // Goes through each error, printing it to an unordered list.
{
echo "<li>$msg</li>";
}
echo "</ul>Please try again.";
}
$validate = array("name", "category", "amount"); // your 3 fields that need to be validated
$error = '';
foreach ($validate as $field) {
if (preg_match('/^[a-z\d ]{3,20}$/i', $$field)) {
$error .= $field;
}
}
Later, based on $error you can show your errors.

Check if multiple strings are empty [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
More concise way to check to see if an array contains only numbers (integers)
PHP checking if empty fields
I have form that submits 10 fields, and 7 of them should be filled, here is how i chek it now in PHP:
if (!$name || !$phone || !$email || !$mobile || !$email || !$state || !$street || ! $city) {
echo '<div class="empty_p">You have empty fields!!!</div>';}
else{
//process order or do something
}
My question is: is there more simple way to do this? Because sometimes I have even more strings to check (12-15)
Another possibility:
$elements = array($name, $email, $mobile);
$valid = true;
foreach ($elements as $element) {
if (empty($element)) {
$valid = false;
}
}
if ($valid) {
// complete
} else {
// alert! some element is empty
}
Something like this?
foreach($_POST as $key => $value)
{
if (empty($_POST[$key]))
{
echo '<div class="empty_p">'.$_POST[$key].' is empty.</div>';
}
}
It's good to be specific about where this data should be expected, e.g. $_POST:
if (!isset($_POST['name'], $_POST['phone'], $_POST['email'], $_POST['mobile'], $_POST['state'], $_POST['street'], $_POST['city'])) {
// something is up
}
You can shorten this code a little bit by creating an array with your required field names:
$required_fields = array('name', 'phone', 'email', 'mobile', 'state', 'street', 'city');
The 'check-for-existence' code can then be simplified to:
foreach ($required_fields as $f) {
if (!isset($_POST[$f])) {
// something is up
}
}
The better way ™
However, you should seriously consider combining both existence and validation / sanitization checks. PHP provides a family of filter functions functions that you can use to validate and/or sanitize your input variables. For example, to get equivalent behavior as above:
$required_fields = filter_input_array(INPUT_POST, array(
'name' => FILTER_UNSAFE_RAW,
'email' => FILTER_VALIDATE_EMAIL,
));
if (is_null($required_fields) || in_array(null, $required_fields, true)) {
// some fields are missing
}
Fields that exist but fail validation will be set to false, so this is how you detect such an event:
foreach ($required_fields as $name => $value) {
if (false === $value) {
// field $name failed validation (e.g. bad email format)
} elseif (!strlen(trim($value))) {
// field is empty
}
}
The best way would be to create some sort of form validator. However you can use this function:
<?php
function isAnyEmpty() {
$total = 0;
$args = func_get_args();
foreach($args as $arg)
{
if(empty($arg)) {
return true;
}
}
return false;
}
$var1 = 1;
$var2 = 'test';
$var3 = '';
if(isAnyEmpty($var1, $var2, $var3)) {
echo 'empty fields!';
}
?>
You could try creating a general validation class that could be reused and be more precise.
Some pseudo code:
<?
class validateFields {
$validators = array(
"name" => array(
"empty" => array(
"rule" => "some regex",
"errorMessage" => "name may not be empty"
),
"noNumbers" => array(
"rule" => "some regex",
"errorMessage" => "No numbers are allowed in the name field"
)
),
"otherVariable" => array(
"atLeast50chars" => array(
"rule" => "some regex",
"errorMessage" => "This field must be at least 50 chars"
)
)
);
public function Validate($post){
$errors = array();
foreach($_POST as $key => $value){
if(!array_key_exists($key, $validators)) {
continue;
}
foreach($validators[$key] as $validator) {
if(!preg_match($validator["rule"], $value) {
$errors[$key] = $validator["errorMessage"];
break;
}
}
}
return $errors;
}
}
?>
Then in your code you could do something like:
$errors = Validate($_POST);
foreach($error as $errorMessage) {
echo $errorMessage . "</br>";
}
Of course you could fancy this up, adding divs with classes right below/beside the concerning input field and load the $errorMessage into there.
I'm sure there's loads of examples out there :)
You can write Foreach loop
foreach($_POST as $key => $value)
{
if (!isset($_POST[$key]) || empty($_POST[$key])
{
echo '<div class="something">You have empty fields!!!</div>';
}
}
<input type="text" name="required[first_name]" />
<input type="text" name="required[last_name]" />
...
$required = $_POST['required'];
foreach ($required as $req) {
$req = trim($req);
if (empty($req))
echo 'gotcha!';
}
/* update */
OK! guys, easy...
You can make it more secure, just with type casting as all we programmers do for out coming data, like $id = (int) $_GET['id'], like $username = (string) addslashes($_POST['username']) and so on...;
$required = (array) $_POST['required'];
And then, what ever comes from post fields let them come, this code just seek what it need.
That is it! Uhh...

Categories