I have these fields: weight, size_1, size_2, size_3
How can I check so minimum one of these fields are filled.
If its under the minimum then it should output "Error, fill one atleast"
I can do this with long if statements, that checks for empty, but is their a better way?
The fields come from an form submission, so it looks like this to get them:
$_POST['weight'];
$_POST['size_1'];
$_POST['size_2'];
$_POST['size_3'];
Assuming they are all in an array:
function check_for_input($array){
foreach($array as $value){
if($value != "") return true;
}
return false;
}
Use it like so:
if(check_for_input($_POST)){ /*...*/ }
else { die("Error, fill one at least"); }
Update with filter:
Assuming they are all in an array:
function check_for_input($array, $filter){
foreach($array as $key=>$value){
if($value != "" && in_array($key, $filter)){
return true;
}
}
return false;
}
Use it like so:
$filter = array('weight', 'size_1', 'size_2', 'size_3', /*...*/);
if(check_for_input($_POST, $filter)){ /*...*/ }
else { die("Error, fill one at least"); }
Related
I am trying to validate an input using a form, through the use of an if statement.
if (isset($_POST['weekly-rate']))
{
$weekly_rate = $_POST['weekly-rate'];
if(!isset($_POST['weekly-rate']))
{
$error_messages[]= 'Weekly rate was not set';
}
else
{
$weekly_rateOK = true;
}
}
else
{
$error_messages[] = 'Weekly rate was not set...';
}
When I run this it gives doesn't give me the output I want, which is Weekly rent was not set. Am I incorrect in thinking that
if(!isset($_POST['weekly-rate']))
{
$error_messages[]= 'Weekly rate was not set';`
Means, if an input is not set, run the error message, weekly rate was not set.
However all I receive is nothing
Your understanding of isset() is correct. However, the form always posts the field back to your backend code which triggers isset() to be true all the time. You may look at using empty() instead.
A simplified version would look like this
$weekly_rateOK = !empty($_POST['weekly-rate']);
if (!$weekly_rateOK) {
$error_messages[] = 'Weekly rate was not set...';
}
You may need to add an integer check if needed.
If you are using a text input/select with a name, then the input/select is always posted and is set, but with an empty string. If it is a checkbox or radio buttons, then they will be set only if the checkbox is checked or a radio button is selected.
I have written a sample validation function, inspired by Laravel. You can check it here, and extend it by adding additional cases:
function validate ($rule_bag, $input) {
$flag = true;
$error_bag = [];
foreach ($rule_bag as $item => $rules){
$rules = is_array($rules) ? $rules : array_filter(explode(',', $rules));
foreach($rules as $rule){
$rule = trim($rule);
switch(mb_strtolower(trim($rule))){
case 'required': {
// checking isset then empty to be compatible with php <= 5.4
if (!isset($input[$item]) || empty($input[$item]))
{
$flag = false;
!isset($error_bag[$item])?$error_bag[$item]=[]:null;
$error_bag[$item][] = $rule;
}
break;
}
default: {
if (isset($input[$item])){
try {
if (!preg_match($rule, $input[$item])){
$flag = false;
!isset($error_bag[$item])?$error_bag[$item]=[]:null;
!isset($error_bag[$item]['regex'])?$error_bag[$item]['regex']=[]:null;
$error_bag[$item]['regex'][] = $rule;
}
}
catch(Exception $e){
echo $e->getMessage();
}
}
}
}
}
}
return $flag ? $flag : $error_bag;
}
HTML markup
<input name="one[name]">
<input name="one[email]">
<input name="two[message]">
...
alot input
..
I pass that two array data from jquery to php, i need check if the field is empty by php and exit when find one of them is empty.
But i dont want do it one by one, can it done by php function like foreach or other?
This is what i tried but fail.
$data_one = $_POST['one'];
$data_two = $_POST['two'];
if (empty( $_POST['one'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Above code keep return field are filled message, whether i fill the input field or not.
Thanks so much.
$allFilled = true;
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
$allFilled = false;
exit('some fields are empty');
}
}
if($allFilled){
exit('all fields are filled');
}
Making use of array_filter and count functions
<?php
$data_one = $_POST['one'];
$data_one_filter = array_filter($_POST['one']); //Remove indexes of null or 0 - certainly name and email can't be 0
$data_one_count = count($_POST['one']); //count actual number of POST variables
$data_two = $_POST['two'];
if (count($data_one_filter) === $data_one_count) {
exit('fields are filled');
} else {
echo('some fields are empty');
// continue other function
}
You are sending data as array. So you seed to check this data as array like this:
$data_one = $_POST['one']['name'];
$data_two = $_POST['two']['message'];
if (empty( $_POST['one']['name'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Try this
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
exit('some field are empty');
}
}
echo "All fields are filled";
I am trying to sanitize 54 variables at once.
Currently I am doing them one by one like so
if($vissuedate != '') {
$vissuedate = filter_var($vissuedate, FILTER_SANITIZE_STRING);
if($vissuedate == ''){
$vvalidate++;
}
}
I have a whole bunch more and want to ask if there is a way to validate all of them in one go?
You could put all the keys from $_GET in an array:
$get_array = array_keys($_GET);
Or, if you want to skip some, you could use your own array:
$get_array = array('name','adress','phone',...);
Then:
foreach($get_array as $v=>$key){
//check if exists
if(!isset($_GET[$key]){
//do something
}
else{
//do sanitizing here }
}
}
Or even, if you want to do different kinds of sanitizing, you could use an array with number:
$get_array = array('name'=>1,'adress'=>1,'phone'=>2,...);
foreach($get_array as $v=>$key){
//check if exists
if(!isset($_GET[$key]){
//do something
}
else{
switch($v){
case 1:
//do something here;
break;
case 2:
//do something else
break;
}
}
}
}
You can iterate through your $_GET like this:
<?php
foreach($_GET as $key => $value) {
if($_GET[$key] != '') {
$vissuedate = filter_var($_GET[$key], FILTER_SANITIZE_STRING);
if($vissuedate == ''){
$vvalidate++;
}
}
Or as you says assign them all to an array and then attempt to validate from there
I have a form with 25+ fields. I want to display a message if ANY of the fields in the array are NOT empty.
$customfields = array('q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10', 'q11', 'q12', 'q13', 'q14', 'q15', 'q16', 'q17', 'q18', 'q19', 'q20', 'q21', 'q22', 'q23', 'q24');
I've taken a look at similar SO questions for verifying that all fields are not empty, i.e.:
$error = false;
foreach($customfields as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "Here's an awesome message!";
} else {
echo "None for you, Glen Coco.";
}
How do I do the opposite - display a message if ANY one or more than one fields in the array are not empty?
Thanks in advance!
I think you want to take a look into the NOT operator.
You can just write this:
if (!empty($_POST[$field])) {
//^ See here the NOT operator
$error = true;
}
For more information see the manual: http://php.net/manual/en/language.operators.logical.php
Do the opposite comparison in the if:
$error = false;
foreach($customfields as $field) {
if (!empty($_POST[$field])) {
$error = true;
break; // get out of foreach loop
}
}
I've created a small function that validates a checkbox control in a form. Im not sure about arrays in functions...
Does the return in the function actually returns an array?
Do i need to declare $arr_category as an array?
In other words, does my function makes sense, need to improve something?
function val_checkbox($name, $required = false) {
global $warning;
$value = array();
if(isset($_POST[$name])) {
$value = $_POST[$name];
} else {
if ($required) {
$warning[$name] = "Required field!";
}
}
return $value;
}
$arr_category = val_checkbox('category'); // category
I've no clue for this function not working !
$value will be an array, no need to declare $arr_caterogy as an array.
It's seem working for me.
You can try this
function val_checkbox($name, $required = false)
{
global $warning;
$value = false;
if(isset($_POST[$name])) $value = $_POST[$name];
else
{
if ($required) $warning[$name] = "Required field!";
}
return $value;
}
$arr_category = val_checkbox('category');
So you can get false as return value if it's invalidated, otherwise the value of the check box will be returned and no need to declare the $arr_category as an array.