How to create a function that validates the name in html form

I am trying to validate a html form using php. But I’m having a hard time since our professor provided us a pre coded activity.

Code goes like this,

if(isset($_POST['save'])){
       
        $firstname = htmlentities($_POST['fn']);
        $lastname = htmlentities($_POST['ln']);
        $email = htmlentities($_POST['email']);
        $status = 'Inactive';
        if(isset($_POST['status'])){
            $status = $_POST['status'];
        }
        $faculty = array(
            "firstname" => $firstname,
            "lastname" => $lastname,
            "email" => $email,
            "academic_rank" => $_POST['rank'],
            "department" => $_POST['department'],
            "admission_role" => $_POST['role'],
            "status" => $status
        );
        array_push($_SESSION['faculty'], $faculty);

        
        header('location: faculty.php');
    }

?>
<form class="add-faculty" action="addfaculty.php" method="post">
                        <label for="fn">First Name</label>
                        <input type="text" id="fn" name="fn" required placeholder="Enter first name">
                        <label for="ln">Last Name</label>
                        <input type="text" id="ln" name="ln" required placeholder="Enter last name">
                        <label for="email">Email</label>
                        <input type="email" id="email" name="email" required placeholder="Enter email">
                        <label for="rank">Academic Rank</label>
                        <select name="rank" id="rank">
                            <option value="None">--Select--</option>
                            <option value="Instructor">Instructor</option>
                            <option value="Asst. Professor">Asst. Professor</option>
                            <option value="Asso. Professor">Asso. Professor</option>
                            <option value="Professor">Professor</option>
                        </select>
                        <label for="department">Department</label>
                        <select name="department" id="department">
                            <option value="None">--Select--</option>
                            <option value="Computer Science">Computer Science</option>
                            <option value="Information Technology">Information Technology</option>
                        </select>
                        <div>
                            <label for="role">Admission Role</label><br>
                            <label class="container" for="admin">Admission Officer
                                <input type="radio" name="role" id="admin" value="Admission Officer">
                                <span class="checkmark"></span>
                            </label>
                            <label class="container" for="interviewer">Interviewer
                                <input type="radio" name="role" id="interviewer" value="Interviewer" checked>
                                <span class="checkmark"></span>
                            </label>

                        </div>
                        <label for="status">Is Status of Employee Active?</label><br>
                        <label class="container" for="status">Yes
                            <input type="checkbox" name="status" id="status" value="Active Employee" checked>
                            <span class="checkbox"></span>
                        </label>
                        <div>
                            <input type="submit" class="button" value="Save Faculty" name="save" id="save">
                        </div>
                    </form>

So, how can I validate or sanitize the user input such as name, lastname, etc. Please help. Thank you.

Have you tried a web search for - php form validation?

No. Sanitize implies that you are going to remove bad things from a value. Other than trimming data, mainly so that you can determine if it was all white-space characters, don’t modify data, as this changes the meaning of the data. Just validate it. If it is valid, use it. If it is not, tell the user what was wrong with it so that they can correct the value.

As to the posted code -

  1. Don’t attempt to detect if the submit button is set. There are cases where it won’t be. Just detect if a post method form was submitted.
  2. htmlentities() is an output function. It is used when you output data in a html context. Do NOT use it on the input data to your form processing code.
  3. Don’t change the names of values. Use the same name for any particular piece of data throughout your code. This just creates more work for you in keeping track of the values and creates more typo mistakes.
  4. Keep the form data as a set, in an array variable, then access elements in this array variable throughout the rest of the code.
  5. For select/option, radio, and checkbox fields, you would validate that the submitted value is one of the permitted choices. See item #12 on this list on how to do this.
  6. For select/option menus, the first choice/prompt should be an empty value and if ‘None’ is a valid choice, it should have its own option entry separate from the prompt entry.
  7. Making an array of the form data, storing it in a session variable, then redirecting is needless coding. Your form processing code, after trimming and validating the data, should use the data on the current page. The only redirect you should do in your form processing code should be upon successful completion, without any errors, to the exact same URL of the current page to cause a get request for that page.
  8. Every redirect needs an exit/die statement to stop code execution.
  9. Your form and form processing code should be on the same page. To get the form to submit to the same page it is on, leave out the entire action=‘…’ attribute.
  10. If you put the <label></label> tags around the field they belong with, you can eliminate the for=‘…’ and id=‘…’ attributes.
  11. The form fields should be ‘sticky’ and be repopulated with any existing value or checked/selected state, so that the user doesn’t need to keep reentering/selecting data should there be a validation error.
  12. For select/option, checkbox, and radio fields, you need to define arrays with the choices, then dynamically produce the fields. This will allow you to modify the choices simply by changing the defining arrays, validate the input simply by checking if the value is in the defining array (see in_array()), and it will make it easy to re-check/re-select existing choices when you redisplay the form.
  13. Any dynamic value that you output in a html context should have htmlentities() applies to it, when you output it.
2 Likes

Validation can happen at two levels here. On the client side, there is form level validation where you can do simple validations like using the “required” attribute on the HTML input elements to ensure that they’re passed on to the PHP backend. I can see that you’ve already done this for “FIrst Name”, “Last Name”, etc.

Then comes server side validation where you can perform more rigorous checks. This happens when you check for the POST request and are just about to process the user’s input (like save it to a database, etc.). Here you’re trying to check if ‘status’ input is posted back and set your variable accordingly:

        if(isset($_POST['status'])){
            $status = $_POST['status'];
        }

This is also one type of validation. In case your validation fails, you have the option of sending an appropriate message to the user using “echo” statement or other means. You can do all kinds of filtering and sanitization here using PHP functions but it all depends on your app’s business logic.

No, not really, because status is a checkbox, what this does is determine if the checkbox was checked or not, both of which are valid results. A checkbox is either on or off, if it is off, it will not be set in the post array.

In order to validate a name (of any other form field), you first need to define what you consider to be valid for that particular field.