开发者

codeigniter form validation and arrays as field names

I have a set of checkboxes in my HTML that look like t开发者_如何学Gohis,

div class="grid_7">
                    <fieldset class="age shadow_50">
                        <label class="legend">Age Group</label>
                            <div class="formRow checkbox">
    <input id="" type="checkbox" name="age[]" value="child" />
    <label>Child</label>
</div>

                            <div class="formRow checkbox">
    <input id="" type="checkbox" name="age[]" value="30's" />
    <label>30s</label>
</div>
                            <div class="formRow checkbox">
    <input id="" type="checkbox" name="age[]" value="60's" />
    <label>60's</label>
</div>

                            <div class="formRow checkbox">
    <input id="" type="checkbox" name="age[]" value="teen" />
    <label>Teen</label>
</div>
                            <div class="formRow checkbox">
    <input id="" type="checkbox" name="age[]" value="40's" />
    <label>40's</label>
</div>

                            <div class="formRow checkbox">
    <input id="" type="checkbox" name="age[]" value="70's" />
    <label>70's</label>
</div>
                            <div class="formRow checkbox">
    <input id="" type="checkbox" name="age[]" value="20's" />
    <label>20's</label>
</div>

                            <div class="formRow checkbox">
    <input id="" type="checkbox" name="age[]" value="50's" />
    <label>50's</label>
</div>
                    </fieldset>
                </div>

I have set a validation rule in my controller that (in my mind) makes sure that a checkbox has been selected,

$this->form_validation->set_rules('age[]', 'age group', 'required|trim');

When testing this however I get an error message for ever checkbox with name age[] I just want to check that age[] is not empty.

How can I achieve this?


You cannot test age[] like that, it is an array. There are a few ways to do this but what you did required is not one of them.

You could use javascript or by running the age[] value through your own custom callback function is one method.

Details for using arrays in CI are here:
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#arraysasfields

If you do it the javascript route, you can use jQuery to iterate through your check boxes (use a class to link them) and just make sure that 1 of them is checked.


Old question but for anyone struggling to do this I believe you can do this by setting a rule on age rather than age[], i.e.

$this->form_validation->set_rules('age', 'age group', 'fnName');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜