Created
October 3, 2021 12:31
-
-
Save Octagon-simon/df03264379a881744d52c961234ef9af to your computer and use it in GitHub Desktop.
How to check if form fields contains a value (!empty) with PHP .
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function checkFormFields($fields, $return) { | |
| $requiredFields = []; //init required fields var | |
| $emptyFields = array(); //init empty fields var | |
| foreach ($fields as $field=>$fieldTag) //loop through the array to find the fields and field tags associated | |
| { | |
| array_push($requiredFields, $field); //push required field to the array | |
| } //end of foreach loop | |
| foreach($requiredFields as $requireField) { | |
| $currentField = $requireField; //store current field | |
| $currentFieldTag = $fields[$currentField]; //store current field tag | |
| if (!($_POST[$currentField])) | |
| { | |
| array_push ($emptyFields, $currentFieldTag); //push the tag name to the empty field | |
| } //end of if field is empty | |
| } //end of check if field has a value | |
| /*** | |
| * | |
| * IF FIELD IS EMPTY BLOCK | |
| * | |
| ***/ | |
| if (isset($emptyFields) && count($emptyFields) > 0) //check if there's an empty field in the variable | |
| { // then loop through | |
| foreach ($emptyFields as $emptyField) { | |
| /*** | |
| * | |
| * CUSTOM USER ALERT ACTION GOES HERE | |
| * | |
| ** */ | |
| echo ' | |
| <script> | |
| document.addEventListener(\'DOMContentLoaded\', function(){ | |
| alert(\''.$emptyField.' is required!\'); | |
| }); | |
| </script>'; //ALERT THE USER | |
| } //END OF empty fields loop | |
| } //end of check if there's an empty field | |
| //if return is set to true | |
| if($return == true) { | |
| if (isset($emptyFields) && count($emptyFields) > 0) { | |
| return(1); | |
| } else { | |
| return (0); | |
| } | |
| } | |
| } //end of function |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Full gist on Hashnode.
Click here to view gist