Welcome Guest, Not a member yet? Register   Sign In
Regex_match for validationg string from selectbox in codeigniter
#1

[eluser]term25[/eluser]
I have this code in my view:

Code:
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:

Code:
$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.
#2

[eluser]Matalina[/eluser]
removed - wrong regex...

I'm not sure how to do it with out square brackets. Is that still an issue as I just read in a google search?
#3

[eluser]boltsabre[/eluser]
Code:
$options = array(  
      '' => '- Select state -',
      'Alabama' => 'Alabama',
      'Florida' => 'Florida',
      'California' => 'California',

);
Now "select state" has no value

Code:
$this->form_validation->set_rules('state', 'State', 'required');

Now this will fail validation if user doesn't select a state because "select state" doesn't have a value.

You really should have some more validation in there, bad people can still alter post/form details. At the very least: "trim|required|alpha".

Problem is though... if your state names reference a table column or something, and it gets changed to "Im a malicious a state" it will break your SQL code, throwing errors and stuff. I'd personally change your state values to numeric values (via an array or someting), that way you can change your validation to something like (if you had 14 states for example:

trim|required|numeric|greater_than[0]|less_than[15]

This way it's impossible for the user to submit anything other than a value you'd expect.
Data cleansing / validation is PARAMOUNT. Do everything in your power to ensure user input only matches what you'd expect.
#4

[eluser]Aken[/eluser]
I would create a base array of your states somewhere (in your controller, in a config file, something), and then I would use a callback validation function to make sure the selected option is in that array. Regex is not a stable way to verify that something is in a defined list of items.
#5

[eluser]boltsabre[/eluser]
Yeah, good idea, just run a in_array($states). Quick, simple, efficient, expandable. Not sure what j was on about with the min & max thing. My bad!




Theme © iAndrew 2016 - Forum software by © MyBB