First, we have to load validation in the controller.
1 | $validation = \Config\Services::validation(); |
Create rules with labels:
1 2 3 | $validation->setRules([ 'name' => ['label' => 'Name', 'rules' => 'required|alpha_numeric'], ]); |
Run validation and get a response list of errors:
1 2 3 | $validation->withRequest($this->request)->run(); errors = $validation->listErrors(); |
Complete code of form validation in the controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public function register(){ $validation = \Config\Services::validation(); $validation->setRules([ 'name' => ['label' => 'Name', 'rules' => 'required|alpha_numeric'], 'phone' => ['label' => 'Phone/Mobile', 'rules' => 'required|greater_than[9]|numeric'], 'email' => ['label' => 'Email Address', 'rules' => 'required|valid_email'], 'organization' => ['label' => 'Organization', 'rules' => 'required|alpha_numeric'], 'designation' => ['label' => 'Designation', 'rules' => 'required'], 'useCase' => ['label' => 'Use Case', 'rules' => 'required'], 'hear_from' => ['label' => 'Hear From', 'rules' => 'required'], 'req' => ['label' => 'Requirement', 'rules' => 'required'] ]); if(!$validation->withRequest($this->request)->run()) { echo $errors = $validation->listErrors(); //This will show All error of form fields. }else{ // No Error, Process form data. $register = $this->HomeModel->register(); // Before this you have to load model on top of controller page as 'namespace'. like: "use App\Models\HomeModel;" } } |