i want to build a validation function(or even class) in php to check for empty fields in a form. The thing is that i want to check the fields one after another and if there is an empty one to send "The -field_name- is empty." If none is empty to continue with the rest of the script...
I have already made it using multiple nested if-else statements....but i was wondering if there is a more compact and programmer friendly way. I've tried using an array which i pass in a foreach statement and then i use a switch loop.
The nested if-else's:
function no_empties($first_name,$last_name,$username,$password,$password2,$user_email,$user_email2)
{
if ( !empty($first_name) )
{ if ( !empty($last_name ) )
{if ( !empty($username ) )
{if ( !empty($password ) )
{if ( !empty($password2) )
{if ( !empty($user_email) )
{if (!empty($user_email2) )
{return TRUE;}
else{ js_msg("Please retype your email!");return FALSE;};
}
else {js_msg("Please enter a -valid- email!"); return FALSE;};
}
else{js_msg("Please retype your password!");return FALSE;};
}
else {js_msg("Please enter a password!" ); return FALSE;};
}
else {js_msg("Pleas enter a username!"); return FALSE;};
}
else { js_msg("Please enter your last name!"); return FALSE;};
}
else { js_msg("Please enter your first name!"); return FALSE;};
}
The second case i described is this:
$fields_array = array("first name"=>$first_name,"last name"=>$last_name,"username"=>$username,"password"=>$password,"retype password"=>$password2,"email"=>$user_email,"retype email"=>$user_email2);
function TEST($fields_array)
{
foreach ($fields_array as $field_name => $input)
{
switch (empty($input)) :
case TRUE: return $output="The -{$field_name}- field is empty
"; break;
case FALSE:return $output= "No field is empty!!! Hooray!
"; break;
endswitch;
}
}
It is working but i cannot use it like this:
if ( TEST($fields_array)==TRUE ): echo $output; else: echo $output; endif;
Moreover it would be perfect if the code was in a form that was irrelevant of how many fields each form has. Someone would just enter an array like $fields = array ("first"=>$first,etc....) .
Any thoughts???????