I want to create a function that checks each filed, If empty add error messages for that field.
If I have the following form:
<form method="post">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="submit" name="submit" value="Submit">
</form>
I tried:
$errors = array();
function empty_check($var, $fieldName){
if( empty($var) ){
$error = $fieldName . ' can\'t be empty';
array_push($errors, $error);
}
}
if (isset($_POST['form_submit'])) {
empty_check( $_POST['name'], 'Name' );
empty_check( $_POST['email'], 'Email' );
print_r($errors);
}
So if I submit the form and both fields are empty, I should get:
Array(
[0] => Name can't be empty
[1] => Email can't be empty
)
But I get error saying that the $errors
inside empty_check
function is not defined.
When I add it to the parameters:
function empty_check($var, $fieldName, $errors){
..
}
Then I need to add that parameter for each time I run the function, And I get an empty array:
empty_check( $_POST['name'], 'Name', $errors );
empty_check( $_POST['email'], 'Email', $errors );
That returns:
Array()
I tried return
, But I get an error [] can't be used for reading
:
function empty_check($var, $fieldName){
if( empty($var) ){
$errors[] = $fieldName . ' can\'t be empty';
return $errors[];
}
}
How should it be?