Search code examples
javascriptalertcodeigniter-3line-breakssweetalert

How to output CodeIgniter validation error messages on SweetAlert with line breaks?


in Controller file:

This is how I json_encode validation errors to View:

if ($this->form_validation->run() == FALSE) { //if validation does not run
    $errors = $this->form_validation->error_array();
    echo json_encode(['error' => true, 'errors' => $errors]);
}

in View file:

if (res.errors) {
    var errorMsgs = "";
    errorMsgs += res.errors.name1 ? res.errors.name1 + "<br/>" : ""; //only if have an error msg.
    errorMsgs += res.errors.name2 ? res.errors.name2 + "<br/>" : ""; //only if have an error msg.
    errorMsgs += res.errors.name3 ? res.errors.name3 : ""; //only if have an error msg.

    // SweetAlert
    swal({ 
        text: errorMsgs // error msg
    });
}

Output on SweetAlert:

This is Name1 field error message.<br/>This is Name2 field error message.<br/>This is Name3 field error message.


Solution

  • found a solution myself. :D

    just use "\n" instead of "<br>"!

    errorMsgs += res.errors.name1 ? res.errors.name1 + "\n" : "";