简体   繁体   中英

How can I get the index of a field array in codeigniter form validation?

I am building a codeigniter data entry form. The form is however mostly dynamically generated in JS based on how many entries need to be submitted.

This means I have to use

<input type='text' name='invoice[]' id='invoice" + index + "' class='form-control' size='20' value=''>

To validate it I use

$this->form_validation->set_rules('invoice[]', 'Invoice field', 'required|trim|alpha_numeric|is_unique[BillingInvoices.InvoiceNumber]',
            array('required' => 'Must enter invoice number.',
                'alpha_numeric' => 'Invoice can only contain letters and numbers',
                'is_unique' => 'Invoice number must be unique in database.')
        );

My problem now is that I have no idea how to get the index of the entry that triggers that rule. My clients need to be able to know which invoice is causing the problem.

I would validate it through javascript too. Most of the major browsers support javascript so almost all of your users will get the error before they submit the form.

This is my proposal:

Step 1: Setup any javascript validation library like validate.js (or any other) in your project.

Step 2: Configure the javascript validation so your users get the error before they submit the form. They will get the error on the affected input.

Step 3: Keep the PHP validation. This is important because javascript can be disabled or even hacked, so we always need to validate user information at the server.

This way you will cover your problem: users will have the error message at the form and your database will always have right information.

Hope this helps, greetings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM