PHP Field validation example

From DreamFactory
Jump to: navigation, search
DreamFactoryTutorialsPHP Field validation example
(Created page with "This script validates that certain fields are in the POST request when creating records. If not, an exception is thrown and 500 error returned to the client. If the script ex...")
 
Line 3: Line 3:
 
be written to the database and the post-process script, if any, will be run.  
 
be written to the database and the post-process script, if any, will be run.  
  
<pre>
+
<source lang=php>
 
// POST /api/v2/db/_table/account triggers script db._table.account.post.pre_process
 
// POST /api/v2/db/_table/account triggers script db._table.account.post.pre_process
 
// This script runs BEFORE records are written to the db.
 
// This script runs BEFORE records are written to the db.
Line 16: Line 16:
 
     throw new \Exception('Annual revenue must be > 0');
 
     throw new \Exception('Annual revenue must be > 0');
 
}
 
}
</pre >
+
</source>

Revision as of 14:43, 3 February 2016

This script validates that certain fields are in the POST request when creating records. If not, an exception is thrown and 500 error returned to the client. If the script exists normally with no exception being thrown then the records will be written to the database and the post-process script, if any, will be run.

// POST /api/v2/db/_table/account triggers script db._table.account.post.pre_process
// This script runs BEFORE records are written to the db.
 
$payload = \Request::json()-&gt;all();
 
if(!array_key_exists('annual_revenue', $payload)){
    throw new \Exception('Missing field annual revenue.');
}
 
if($payload['annual_revenue'] &lt;= 0){
    throw new \Exception('Annual revenue must be > 0');
}