Jump to content
php.lv forumi

POST mainīgo pārbaude


ArnisR

Recommended Posts

Kā pārbaudīt visus caur HTML formu padotos POST mainīgos, lai nevajadzētu rakstīt katram mainīgajam savu pārbaudi, piemēram:

 

if(empty($_POST["name"]) or empty($_POST["surname"]) or empty($_POST["email"]) ... )
{
die("Nav aizpildīti visi formas lauki!");
}

Link to comment
Share on other sites

Nu $_POST ir masīvs, vai ne? Un lai masīvam izietu cauri?

 

Pēc piecām minūtēm...

 

Aizrāvos un uzrakstīju funkciju, kurai ir jānorāda parametrs, kam ir jābūt masīvam (asociatīvam, 1D). Funkcija atgriež "true", ja viss ir kārtībā (visi masīva elementi ir aizpildīti), bet "false", ja vismaz viens no tiem ir neaizpildīts.

 

Piemērs:

 

$_POST['email'] = '';

 

Kods ir tikai kā idejas demonstrēšana!

 

function checkEmptiness( array $array ) {

$errors = 0;


forEach ( $array as $key => $value ) {

	if ( empty( $value ) ) {

		++$errors;

	}

}


return ( ( $errors === 0 ) ? true : false );

}


$testArray = array(
'x' => 1,
'y' => 3,
'z' => 23,
//'q' => null
);


var_dump( checkEmptiness( $testArray ) );

Link to comment
Share on other sites

Bla bla, yep, yep

 

Klau, šitais tev neliekas muļķīgi? :))

 

return $something ? true : false;

 

EDIT, mana interpretācija par funkciju:

 

<?php
/**
* Pārbaudam, vai nepieciešamās vērtības eksistē masīvā
* @param array $arr Pārbaudāmais masīvs  
* @param array $required Masīvs ar indeksu nosaukumiem
* @return bool
*/
function checkEmpty($arr, $required){
$arr = array_flip(array_filter($arr));
$tmp = array_intersect($arr, $required);
return count($tmp) == count($required);
}
var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "3", "d" => "4"), array("a", "b", "c", "d"))); //T
var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "3", "d" => ""), array("a", "b", "c", "d"))); //F
var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "3", "d" => ""), array("a", "b", "c"))); //T
var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "0"), array("a", "b", "c"))); //F, jo "0" ir empty
var_dump(checkEmpty(array("a" => "1", "b" => "2", "c" => "0"), array("a", "b", "d"))); //F
?>

Edited by briedis
Link to comment
Share on other sites

Klau, šitais tev neliekas muļķīgi? :))

 

return $something ? true : false;

 

Es gribēju, lai atgriež "boolean". Es jau teicu, ka funkcija nav funkcijas vērta... tikai lai parādītu domu, lai autors saprastu "kā".

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...