Welcome Guest, Not a member yet? Register   Sign In
[ASK[ Validate input array
#1

(This post was last modified: 01-05-2021, 02:50 AM by maulahaz.)

I'd like to validate these input array below, but it still get "Success" even though the field "answer_opt[]" I kept empty, 
but for field "question" is working normal. Please help.


Info: I'm using CI 4.0.2.

View file:
Code:
<div class="form-group row">
    <label for="question" class="col-sm-2 col-form-label">Question</label>
    <div class="col-sm-9">
        <textarea class="form-control" id="question" name="question"></textarea>
    </div>
</div>

<div class="form-group row">
    <label for="answer_opt1" class="col-sm-2 col-form-label">Option 1</label>
    <div class="col-sm-9">
        <input type="text" class="form-control" id="answer_opt1" name="answer_opt[]" value="" placeholder="Option of answer 1">
    </div>
</div>
<div class="form-group row">
    <label for="answer_opt2" class="col-sm-2 col-form-label">Option 2</label>
    <div class="col-sm-9">
        <input type="text" class="form-control" id="answer_opt2" name="answer_opt[]" value="" placeholder="Option of answer 2">
    </div>
</div>
<div class="form-group row">
    <label for="answer_opt3" class="col-sm-2 col-form-label">Option 3</label>
    <div class="col-sm-9">
        <input type="text" class="form-control" id="answer_opt3" name="answer_opt[]" value="" placeholder="Option of answer 3">
    </div>
</div>


Controller:
Code:
protected $validation;

public function __construct()
{
    // Services:
    $this->validation = \Config\Services::validation();
}

function create()
{
    $valid = $this->_modifyValidation();

    if ($valid){             
        echo "Success";
    }else{
        $data['errors'] = array($this->validation->listErrors());             
    }

    return view('quiz/view_file', $data);
}

function _modifyValidation()
{
    $valid = $this->validate([
        'question'=> ['label' => 'Question', 'rules' => 'required'],
        'answer'=> ['label' => 'Answer', 'rules' => 'required'],
        'answer_opt.*'=> ['label' => 'Answer option', 'rules' => 'required'],
    ]);

    return $valid;
}
Reply


Messages In This Thread
[ASK[ Validate input array - by maulahaz - 01-05-2021, 02:45 AM



Theme © iAndrew 2016 - Forum software by © MyBB