everyone! I've been having a terrible time trying to figure out why my form validation doesn't recognize empty fields and return them as errors.
Here is a function I use to check the fields:
function check_required_fields($required_array) {
$field_errors = array();
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$field_errors[] = $fieldname;
}
}
return $field_errors;
}
Then, my form is process like this:
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('client', 'banner', 'district', 'store', 'position', 'first_name', 'last_name', 'email', 'password');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
and an IF statement checks for errors:
if ( empty($errors) ) {
$query =
The problem is, even if my fields are empty (and I checked them with var_dump($_POST)) PHP performs the $query. I think there is something wrong with the function. I hope someone can help me spot the error!
Here is the gist of my HTML code:
<form action="registration.php" method="post">
<label for="first_name" class="medium">First Name</label>
<input type="text" name="first_name" class="textbox short_field">
<button type="submit" name="submit" value="submit" class="form-submit-button">SUBMIT</button>
</form>
I also use the following functions to validate string length and it works just fine:
function check_max_field_lengths($field_length_array) {
$field_errors = array();
foreach($field_length_array as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $field_errors[] = $fieldname;
}
}
return $field_errors;
}
and
$fields_with_lengths = array('first_name' => 30, 'last_name' => 30, 'email' => 50, 'password' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
"The problem is, even if my fields are empty (and I checked them with var_dump($_POST)) PHP performs the $query."
Your problem is caused by this condition: $var != 0. Php can cast variables of different types between each other, so empty string is equal to 0. Proof:
<?php
$var = '';
var_dump($var == 0);
Output: bool(true)
Now look at this sample, imitating, how php processes your condition:
<?php
$var = '';
var_dump(empty($var));
var_dump((empty($var) && $var != 0));
Output:
bool(true)
bool(false)
In the 2-nd case the boolean function returns false, therefore, the variable won't be added to the array of errors.
I don't know, what do you want to achieve with this: $var != 0. But the condition:
if (!isset($_POST[$fieldname]) ||
(empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$field_errors[] = $fieldname;
}
can be easily switched to this:
if (empty($_POST[$fieldname])) {
$field_errors[] = $fieldname;
}
Related
So I have the following code:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
if (empty($obj->birthday) || $obj->hire_date) {
$record->fill([
'birthday' => '',
'hire_date' => ''
]);
} else {
$record->fill($arr);
}
} else {
$record->timestamps = false;
}
Where I'm checking if $obj->birthday or $obj->hire_date is empty, and then define them as empty strings, but here is the problem.
I want to be able to call $record->fill($arr) regardless and prepopulate all my fields on the empty check, but for some reason I can't seem to figure out out.
So heres the logic:
Empty hire_date? set as ''.
Empty birthday? set as ''.
Populate the rest of the fields..
Both hire_date and birthday not empty? Populate all fields.
You can try this:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$filllArray = $arr;
if (empty($obj->birthday) {
$record->fill([
'birthday' => ''
]);
unset($filllArray['birthday']);
}
if (empty($obj->hire_date)) {
$record->fill([
'hire_date' => ''
]);
unset($filllArray['hire_date']);
}
$record->fill($filllArray);
} else {
$record->timestamps = false;
}
Update 1: Copy the $arr to $filllArray and update the new array to determine what should be filled or not.
I know you've accepted an answer. This is a slightly different way of achieving the same thing (If I understood the question correctly)
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$fa = [];
empty($obj->birthday) ? $fa['birthday'] = '' : $fa['birthday'] = $obj->birthday;
empty($obj->hire_date) ? $fa['hire_date'] = '' : $fa['hire_date'] = $obj->hire_date;
$merged_arr = array_merge($arr, $fa);
$record->fill($merged_arr);
} else {
$record->timestamps = false;
}
I have a basic form with a dozen fields (I would take 3 for example):
<input type="text" name="user_first_name" class="form-control" pattern="[A-Za-z-]+" required />
<input type="text" name="user_last_name" class="form-control" pattern="[A-Za-z-]+" required />
<input type="tel" name="user_phone" class="form-control" />
...
Only the phone number can be empty, the last name and first name are obligatory and can contain only letters and dashes (the technical constraints were imposed on me by our old ERP)
I created a function to clean up all my fields that looks like this:
public function sanitizeInfo($user_first_name, $user_last_name, $user_phone) {
$user_first_name = preg_replace('/[^A-Za-z-]/', '', $user_first_name);
$user_last_name = preg_replace('/[^A-Za-z-]/', '', $user_last_name);
$user_phone = (isset($user_phone) and !empty($user_phone)) ? preg_replace('/[^A-Za-z0-9+-.)(]/', '', $user_phone) : NULL;
$array = array(
"first_name" => $user_first_name,
"last_name" => $user_last_name,
"phone" => $user_phone
);
return $array;
}
In my PHP script I make this first check:
$fields = array('user_first_name', 'user_last_name');
$error = FALSE;
foreach ($fields as $fieldname) {
if(!isset($_POST[$fieldname]) or empty($_POST[$fieldname])) {
$error = TRUE;
$message = 'err';
}
}
if (error === TRUE) {
echo "Error !"
} else {
$info = sanitizeInfo($_POST['user_first_name'], $_POST['user_last_name'], $_POST['user_phone']);
...
** QUERY **
}
I want to check, before sending this in database, that the fields are not empty (only the telephone number can be NULL)
But the problem right now is that I do not know if my non-required fields exist and especially my sanatizeInfo function is problematic because it allows to put empty fields in database
Example:
The user enters "!! -" as firstname and the sanitizeInfo function returns "" because the preg_replace to delete these characters
How to avoid this?
All you need to do is calling the function sanitizeInfo before checking empty fields and replacing your foreach loop with a simple array_search function.
This can be implemented as follows:
$fields = array('user_first_name', 'user_last_name');
$error = FALSE;
$values = sanitizeInfo($fields[0], $fields[1], #$fields[2]);
$arSear = array_search('', $values);
if ($arSear !== FALSE && $arSear != 'phone'){
$error = TRUE;
$message = 'The field `'.$arSear.'` is empty.';
}
if ($error) {
echo 'Error: '. $message;
} else {
// QUERY ....
}
As a matter of consistency, I recommend always using && and || in php versus AND and OR. This will prevent any trip ups regarding precedence. 'AND' vs '&&' as operator
I have a user defined function, it takes one argument as an array for the form required fields. It checks if these fields are empty or not. If they are empty it will return a message and stop processing the form.
<?php
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
}
}
return "You have errors";
}
$required_array = array('name', 'age');
if (isset($_POST['submit'])) {
echo check_required_fields($required_array);
}
?>
<html>
<body>
<form action="#" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
The function is returning this error even when the form required fields are filled? how to fix this?
How can i use just use the function with out writing the word echo before its name?
I want to use this function so i don't have to manually write the if and else statement for every field in the form.
I think you want to do like this?
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
return "You have errors"; //This indicates that there are errors
}
}
}
or why not just:
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname])) {
return "You have errors"; //This indicates that there are errors
}
}
}
UPDATE:
Change:
$required_array = array('name', 'age'); //This just sets strings name and age into the array
to:
$required_array = array($_POST['name'], $_POST['age']); //This takes the values from the form
This question already has answers here:
How do I add on multiple $_POST['row'] and variables? [closed]
(2 answers)
Closed 9 years ago.
I have many isset checkings:
if (isset($_POST['name']) && isset($_POST['day']) && isset($_POST['month']) && isset($_POST['year']) && isset($_POST['email']) && isset($_POST['email2'])&& isset($_POST['pass']) && isset($_POST['pass2']))
{
Is there a way to short it?
$isset = array
(
'name', 'day', 'month', 'year',
'email', 'email2', 'pass', 'pass2'
);
foreach ($isset As $set)
{
if (!isset($_POST[$set]) || empty($_POST[$set]))
{
echo 'error';
break;
}
}
Is that correct?
You could use a loop and empty only:
$keys = array('name', 'day', 'month'); // ...
foreach ($keys as $key) {
if (empty($_POST[$key])) {
// fail
break;
}
}
Or you could use array_diff_key():
if (array_diff_key(array_flip($keys), $_POST)) {
// fail (some keys not present in $_POST)
}
isset() can take multiple arguments, so you can shorten it simply like this.
if (isset($_POST['name'], $_POST['day'], $_POST['month'], $_POST['year'], $_POST['email'], $_POST['email2'], $_POST['pass'], $_POST['pass2']))
PHP Docs: http://php.net/manual/en/function.isset.php
Define a function like this:
function getPost($key, $default = null) {
if (isset($_POST[$key])) {
return $_POST[$key];
}
return $default;
}
Then you can skip the isset verification. If there's no sucho value, by default, the function will return null.
If you are sending these from an input form and your default value attribute is value="" then it will still be set in $_POST.
For example, if the previous page has:
<input type="text/css" id="email" name="email" value="" />
Then if the user leaves it blank, isset($_POST['email']) will return true, and $_POST['email'] will have a value of "". That's useless, right?
Try this.
$c = 0;
foreach($_POST as $key => $value)
{
$value = trim($value);//Makes sure there's no leading, or ending spaces. Safe to guard against a string that is " " instead of "".
if(strlen($value) > 0)
{
$c++;
}
else
{
echo "$_POST['" . $key . "'] has a problem.";
}
break;
}
Then your new if statement for whatever conditions you had in mind could be:
if($c == 8)//8 being the number of keys you're expecting to not be "" or null.
{
//Your conditions.
}
This is good to keep in mind. You are only testing 8 array keys, but what if you had 800? Something like this would be a necessity.
Depends on what you are doing, if it is to set a value, the ternary operator works wonders:
isset($_POST['day'])?$day=_POST['day'] :$day='';
after that line, $day is always set and you only test with if($day).
If there are many values, you can always run this assignment in a loop:
foreach(array('day','month','name') as $var)
{
isset($_POST[$var])?$$var=$_POST['$var']:$$var='';
}
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...