Wednesday, March 8, 2017

How to Validate and Sanitize Form Checkbox Array?

I'm using OctoberCMS based on Laravel and Twig.

I have a form with checkboxes queued[]. They are submitted and deleted with Laravel using a loop.

It all works but how can I validate and sanitize the array?

Validate requires an asterisk *? '*' => Input::get('queued')?

Sanitize, I get the error trim() expects parameter 1 to be string, array given.

Form

<form method="POST" action=""> 
    <input type="hidden" name="_handler" value="onDelete" />
    <input type="checkbox" name="queued[]" value="item1" />
    <input type="checkbox" name="queued[]" value="item2" />
    <input type="checkbox" name="queued[]" value="item3" />
    <button type="submit" name="submit" value="delete">Delete Checked</button>
</form>

PHP

public function onDelete() {
    $checkboxes = '';
    $checkboxes = isset($_POST['queued']) ? $_POST['queued'] : array();

    foreach($checkboxes as $file) {        
        File::delete("$file");
    } 
}

Validator

$validator = Validator::make(
    [
        '_handler' => Input::get('_handler'),
        'queued' => Input::get('queued'),
        'submit' => Input::get('submit')
    ]
);

Sanitize

function sanitize_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = strip_tags($data);
    $data = htmlspecialchars($data);
    return $data;
}



via Matt McManis

Advertisement