PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 30, 2022

[FIXED] in codeigniter, i am using same name for multiple inputs(type="text"), during submit i want to allow at least one value, how can i validate?

 January 30, 2022     codeigniter, codeigniter-2, codeigniter-3, php     No comments   

Issue

My code snippet:

<div class="col-sm-2">
    <label>Weight</label>
    <?php for($i=0;$i<4;$i++){ ?>
      <input type="text" placeholder="Weight" name="weight[]" id="weight_<?php echo $i; ?>" class="form-control weight_cls" />
    <?php } ?>
    <div class="err"><?php echo form_error('weight[]'); ?></div>
</div>

If i use following CI validation:

$this -> form_validation -> set_rules('weight[]', 'Weight', 'required|numeric');

Then it will not allow until fill all fields..

I want to allow at least one.. how can i??


Solution

Create your own validation method :

$this->form_validation->set_rules('weight[]', 'Weight', 'callback_weight_check');

And in the same controller :

public function weight_check($weight)
{
     if(count(array_filter($weight)) == 0) {
         $this->form_validation->set_message('weight_check', 'Fill at least one value');
         return false;
     }

     return true;
}

More infos : https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods



Answered By - Vincent Decaux
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing