• Call Us:
  • - Mail Us:

Validation forms in Codeigniter 4

Please Login and enroll in this course to view the lesson.

  • How to validate the forms in Codeigniter 4?
  • How can you create the HTML forms in Codeigniter 4?

In this section, you will learn how you can create the HTML forms and validate the that fields using Codeigniter 4.

This is your Method to create the HTML form in ci4.

public function register()
    {
        helper('form');
        echo view('user/register');
    }

This is HTML code/view

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Welcome in Register</title>
</head>
<body>
    <div>
        <?php
        $myvalidation  = ConfigServices::validation();
        echo $myvalidation->listErrors();
        ?>
    </div>
    <?php echo form_open_multipart('libraries/newuser',['class'=>'muclass','id'=>'myId'])?>
    <p>
        <label>Your Name</label>
        <?php echo form_input('name','',['class'=>'muclass','id'=>'name']); ?>
    </p>
    <p>
        <label>Your Surname</label>
        <?php echo form_input('surname','',['class'=>'muclass','id'=>'surname']); ?>
    </p>
    <p>
        <label>Your City</label>
        <?php echo form_input('city','',['class'=>'muclass','id'=>'city']); ?>
    </p>
    <?php echo form_submit('submit','Register Now'); ?>
    <?php echo form_close(); ?>
</body>
</html>

In validation.php file use this code

public $newUser = [
        'name'=>'required',
        'surname'=>'required|min_length[2]|max_length[8]',
        'city'=>'required',
    ];

 

Validate method

public function newuser()
    {
        $userTable = new ModUser();
        //dd($userTable);
        $request  = ConfigServices::request();
        $validation  = ConfigServices::validation();
        $randomName = '';
        //dd($validation->getRuleGroup('newUser'));
        if (!$this->validate($validation->getRuleGroup('newUser'))) {
            $this->register();
        }
        else{
            //echo 'fine';

            
            $userData = [
                'u_name'=>$request->getPost('name'),
                'u_surname'=>$request->getPost('surname'),
                'u_city'=>$request->getPost('city'),
                

            ];
            
            var_dump($userData);
        }

    }