Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly Validate Form Fields in PHP

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.

like image 830
Tarik Avatar asked May 23 '26 14:05

Tarik


2 Answers

<?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...
}
like image 118
Swift Avatar answered May 25 '26 02:05

Swift


// 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
}
like image 25
Alix Axel Avatar answered May 25 '26 02:05

Alix Axel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!