When I have fields under a form tag, I use isset() function such as below:
if(isset($_POST) and isset($_POST['title']) and $_POST['date'])
{
//something;
}
and it gets bigger when I validate more fields. I am looking for any easy way of validate whether they are all filled or not in server-side with PHP.
Maybe something which navigates all the fields and check whether they are filled as required.
<?php
$fields = array('field1', 'field2', 'field3', ...etc...); // Array of fields
$valid = true; //Assume all fields are correct and set this to false if not
foreach($fields as $field) {
if(!array_key_exits($field, $_POST)) {
$valid = false; // At least one key isn't set
break;
}
}
if($valid) {
// All fields are good
} else {
//Your user failed...
}
// required fields
$fields = array('title', 'date', 'email');
// optionally ignore blank posted values
$_POST = array_filter(array_map('trim', $_POST), 'strlen');
if (count(array_intersect_key($_POST, array_flip($fields))) == count($fields))
{
// all the required fields were posted
}
else
{
// ...not
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With