9891

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.

Answer1:

<?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... }

Answer2:

// 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 }

Answer3:

$_POST is an array, so you can fetch its element using foreach and then test each element if it is empty or no, collecting errors if there and at the end send one error message.

Answer4:

I've found it amongst comment section on PHP Manual...

A little function which take an array as keys:

<?php //note the s in the function name (keys) function array_keys_exists($array,$keys) { foreach($keys as $k) { if(!isset($array[$k])) { return false; } } return true; } ?> //useful to validate a form for example <form> <input type="text" name="field1" /><br /> <input type="text" name="field2" /><br /> <input type="text" name="field3" /><br /> <input type="text" name="field4" /><br /> <input type="text" name="field5" /><br /> </form> <?php if(!array_keys_exists($_POST, array("field1","field2","field3","field4","field5") )) { //some fields are missing, dont do anything (maybe hacking) } else { //code ... } ?>

Answer5:

A more reusable solution would be to write a small function to verify a list of keys exist, such as

function array_keys_exist($keys, $search) { // If we were passed a single key, use existing function if (!is_array($keys)) { return array_key_exists($keys, $search); } // If there are no keys in $search that are not in $keys // We have all the keys return 0 == count(array_diff($keys, array_keys($search))); }

which could then be used for all your forms like this:

$requiredFields = array('title', 'date', 'details'); if (array_keys_exist($requiredFields, $_POST)) { // Do your thing }

Frankly, I'm not sure why this isn't already a built-in function

Recommend

  • How to populate html table with info from list in django
  • Prevent page break in text block with iText, XMLWorker
  • Shouldn't else be indented in the below code
  • cordova is not defined - cordova.js has already been loaded :: Ionic
  • jQuery: add elements until a particular height is reached
  • Combining two different ActiveRecord collections into one
  • Web.config system.webserver errors
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • How to use carriage return with multiple line?
  • Why value captured by reference in lambda is broken? [duplicate]
  • Retrieving value from sql ExecuteScalar()
  • Different response to non-authenticated users and AJAX calls
  • C# - Serializing and deserializing static member
  • HTML download movie download link
  • Incrementing object id automatically JS constructor (static method and variable)
  • Modifying destination and filename of gulp-svg-sprite
  • How to handle AllServersUnavailable Exception
  • How to model a transition system with SPIN
  • VBA Convert delimiter text file to Excel
  • ORA-29908: missing primary invocation for ancillary operator
  • Do create extension work in single-user mode in postgres?
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • 0x202A in filename: Why?
  • How to disable jQuery.jplayer autoplay?
  • KeystoneJS: Relationships in Admin UI not updating
  • Hits per day in Google Big Query
  • Why joiner is not used after Sequence generator or Update statergy
  • How to stop GridView from loading again when I press back button?
  • File not found error Google Drive API
  • Authorize attributes not working in MVC 4
  • Bitwise OR returns boolean when one of operands is nil
  • sending mail using smtp is too slow
  • Checking variable from a different class in C#
  • Busy indicator not showing up in wpf window [duplicate]
  • Recursive/Hierarchical Query Using Postgres
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF