Derfder Derfder - 2 months ago 44
PHP Question

Regex_match for validationg string from selectbox in codeigniter

I have this code in my view:

echo form_label('State', 'state');
$options = array(
'No state' => '- Select state -',
'Alabama' => 'Alabama',
'Florida' => 'Florida',
'California' => 'California',

);
echo form_dropdown('state', $options);
echo form_error('state', '<div class="error">', '</div>');


And in my controller this:

$this->form_validation->set_rules('state', 'State', 'required|regex_match[??????]');
if ($this->form_validation->run() == FALSE)
{
// VALIDATION ERROR
$this->load->view('page_registration');
}
else
{
// VALIDATION SUCCESS
....
....
....


My question is what to type inside regex_match instead of the question marks, so when everythng else instead of No state is selected it will succed. If you select No state, then the registration page reload and shows the error.

I need the regular expression code between the square brackets for regex_match.

Thanks in advance.

Answer

Why dont you put a Zero in the array

$options = array(   
      '0' => '- Select state -',
      'Alabama' => 'Alabama',
      'Florida' => 'Florida',
      'California' => 'California',

);

And then in your controller you might use

$this->form_validation->set_rules('state', 'State', 'required|alpha');

EDIT:

If you want to stick with regex and validate NOT ALPHA you can use something like this

$this->form_validation->set_rules('state', 'state', 'trim|required|regex_match[/^[a-zA-Z]$/]');

Hope it helps

Comments