Shorter way of POSTs validation?
I always do POST's check validation, sometime its get too messy and long. What is the best way to keep it shorter and tidy?
Example:
if (isset($_POST['albumName']) && trim($_POST['albumName']) != "" && isset($_POST['slugName']) && $_POST['slugNa开发者_开发问答me'] != "" && is_numeric($_POST['PhotoCatID'])) {
//All good
}
The standard Filter extension may have what you're looking for, filter_input
in particular:
$albumName = filter_input(INPUT_POST, 'albumName', FILTER_SANITIZE_STRIPPED);
$slugNamed = filter_input(INPUT_POST, 'slugName', FILTER_SANITIZE_STRIPPED);
$PhotoCatId = filter_input(INPUT_POST, 'PhotoCatId', FILTER_SANITIZE_NUMBER_INT);
(I personally ended up writing wrappers named filter_get
, filter_post
and filter_request
just to make the lines a bit shorter...)
If you are looking to cut down your duplicate code and improve your logic, look into creating a validation class, will allow you to centralise all the validation logic.
Lots of resources on validation classes:
- http://www.phpclasses.org/browse/file/5200.html
- http://www.devshed.com/c/a/PHP/Building-An-Extensible-Form-Validator-Class/
Also you have PHP built-in FILTER extension, which allows you to both sanitize and validate data.
- http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/
First. Write vertically, not horizontally.
If you have several statements, write it one under another, not in one enormous line
Next, some validations can be be applied in a loop:
foreach ($_POST as $key => $value) $_POST[$key] = trim($value);
Next, some statements can be shortened.
$err=array();
if (empty($_POST['albumName'])) $err[]= "Album name is empty";
if (empty($_POST['slugName'])) $err[]= "Slug name is empty";
if (!is_numeric($_POST['PhotoCatID'])) $err[]= "Wrong parameters";
if(!$err) {
//All good
}
The rest is depends on your needs.
For IDs you can save yourself alot of trouble and just typecast them to int
$id = (int)$_POST['id'];
If the value is not valid, $id will be set to 0.
精彩评论