Skip to content

Instantly share code, notes, and snippets.

@edomaru
Created June 29, 2016 02:26
Show Gist options
  • Save edomaru/afca579a6c766af1ef1fc7d78b70e84f to your computer and use it in GitHub Desktop.
Save edomaru/afca579a6c766af1ef1fc7d78b70e84f to your computer and use it in GitHub Desktop.
codeigniter ajax array validation

Controller

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Users extends CI_Controller {
	
	public function create()
	{

		$this->load->view("header");
		$this->load->view("users/create");
		$this->load->view("footer");
	}

	private function set_mass_rules($field, $label, $rules)
	{
		if (isset($_POST[$field]))
		{
			foreach ($_POST as $key => $value) 
			{
				if (is_array($value)) 
				{
					foreach ($value as $fkey => $fval) {
						$this->form_validation->set_rules("{$field}[{$fkey}]", "{$label} {$fkey}", $rules);
					}
				}				
			}
		}
	}

	public function save()
	{
		$data = array('success' => false, 'messages' => array());

		$this->load->library('form_validation');
		$this->form_validation->set_rules("username", "Username", "trim|required");
		$this->form_validation->set_rules("email", "Email", "trim|required|valid_email");
		$this->form_validation->set_rules("password", "Password", "trim|required");
		$this->form_validation->set_rules("password_confirm", "Password Confirm", "trim|required|matches[password]");
		$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
		$this->set_mass_rules("kontak", "Kontak", "required"); // <---

		if ($this->form_validation->run()) {
			$data['success'] = true;
		}
		else {
			foreach ($_POST as $key => $value) 
			{
				if (is_array($value)) 
				{
					foreach ($value as $fkey => $fval) {
						$data['messages']["{$key}_{$fkey}"] = form_error("{$key}[{$fkey}]");
					}
				}
				else {
					$data['messages'][$key] = form_error($key);
				}
			}
		}

		echo json_encode($data);
	}
}

View

<input type="text" name="kontak[0]" id="kontak_0" class="form-control">
<input type="text" name="kontak[1]" id="kontak_1" class="form-control">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment