Welcome Guest, Not a member yet? Register   Sign In
Validate input fields with dynamic names
#1

[eluser]Prophet[/eluser]
Hi everyone. My brain must not be working properly tonight, this is my second topic in an hour :roll:

One of my pages generates input fields dynamically:
Code:
foreach ($store['stock'] as $stock)
{
    <input name="<?=$stock['id']?>" value="<?=$stock['count']?>" size="3" />
}

Each input is the count of how much of a particular product is in stock. These are the only inputs in the form so my application just grabs every $_POST (except "submit" of course) and assumes it's one of those inputs. This works fine, even though I realise it is not secure at all - I'll fix that eventually...

My problem is that I need to validate each field to check that it is_natural_no_zero. Is there a way to do this for inputs that have dynamic names? Can I do something like:
Code:
$this->form_validation->set_rules($_POST, 'Count', 'required|is_natural_no_zero');
$this->form_validation->set_rules('submit', 'Submit', 'required');

Also any tips on how to make my form more secure are welcome :red:
#2

[eluser]Prophet[/eluser]
Okay I might have just found a solution to my own problem. It definitely works but is it good coding practice to do things like this?

Creating the inputs:
Code:
<input name="count_<?=$stock['id']?>" value="<?=$stock['count']?>" size="3" />

Form validation:
Code:
foreach ($_POST as $key => $val)
{
    if (substr($key, 0, 6) == 'count_')
    {
        $this->form_validation->set_rules($key, 'Count', 'required|is_natural|maxlength[7]');
    }
}




Theme © iAndrew 2016 - Forum software by © MyBB