Wednesday, October 30, 2013

HTML5 Validation with CodeIgniter Form Helper

Setting up validation in HTML5 is a nifty task. In this post I'll show you how to set HTML5 validation using Codeigniter Form Helper.
$this->load->helper('form');
echo form_open('');
$data = array(
   'name' => 'search',
   'id' => 'search',
   'maxlength' => 100,
   'placeholder' => 'Search',
   'pattern' => '.{3,}',
   'oninvalid' => "setCustomValidity('Minimum 3 characters.')",
   'oninput' => "setCustomValidity('')",
   'required' => 'required'
);
echo form_input($data);
echo form_close();
So, what this will generate is a input search field with custom HTML5 validation that will only accept minimum of three characters. The only thing to remember is  that we only write 'required' in HTML5 input field but for Codeigniter to understand we need to set required => 'required' (line 11) in the data array

The above code will produce the following html:

If you don't understand the HTML5 attributes used above: refer to the HTML5 Reference. Cheers!