Home > Enterprise >  Using PHP, How to create a function that validates the name in html form
Using PHP, How to create a function that validates the name in html form

Time:09-28

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.

So, his code is like this.

if(isset($_POST['save'])){
        //sanitize user inputs
        $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);

        //redirect user to faculty page after saving
        header('location: faculty.php');
    }

?>

this is where the form will be saved, as for the html form. I Did not wrote the whole code as it is the same.

         <label for="fn">First Name</label>
         <input type="text" id="fn" name="fn" required placeholder="Enter first name">
                           
         <input type="submit"  value="Save Faculty" name="save" id="save">
   

I am trying to learn php...Thanks in advance

CodePudding user response:

Try this one

 if(isset($_POST['save'])){
    if (preg_match('~[0-9] ~', $_POST['fn']) || preg_match('~[0-9] ~', $_POST['ln'])) {
        // show error like "please enter valid name", or whatever you want
    }else{
        $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);

        //redirect user to faculty page after saving
        header('location: faculty.php');
    }
}    

CodePudding user response:

You can use validator like this. This will check have you sent fn or not.

$validator = Validator::make($request->all(), [
                        'fn'    =>  'required',
    
                    ]);
    
            if ($validator->fails()) {
                        
                        return back();
            }
  •  Tags:  
  • php
  • Related