Derfder
Derfder

Reputation: 3324

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.

Upvotes: 0

Views: 1494

Answers (2)

grifos
grifos

Reputation: 3381

Try: /^(?!(No state)).*$/ (I wrapped the regexp for pregmatch, sorry that i forgot earlier)

Translated : The string should not begin with 'No state'. ( so 'No state my friend' would failed)

Result:

preg_match('/^(?!(No state)).*$/', 'No state', $matches);
array()

preg_match('/^(?!(No state)).*$/', 'Alabama', $matches);
array ( 0 => 'Alabama' )

Regex are usefull so try to learn the syntax (google for a tutorial, there is plenty availables)

Upvotes: 2

Carlos Quijano
Carlos Quijano

Reputation: 1576

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

Upvotes: 2

Related Questions