Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 909
Pasindu Jayanath Avatar asked Jan 28 '26 00:01

Pasindu Jayanath


2 Answers

found a solution myself. :D

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

errorMsgs += res.errors.name1 ? res.errors.name1 + "\n" : "";
like image 102
Pasindu Jayanath Avatar answered Jan 30 '26 13:01

Pasindu Jayanath


Case https://sweetalert.js.org/ VS https://sweetalert2.github.io/

For : https://sweetalert.js.org/

As documentation says : html is no longer used.

https://sweetalert.js.org/docs/

Instead use the content object.

swal({
  content: "input",
});

For : https://sweetalert2.github.io/

if you are using this this SweetAlert2 plugin from here

https://sweetalert2.github.io/

You can get your desired result with html

swal({
        title: "<i>Title</i>", 
        html: 'A custom message.</br> jkldfjkjdklfjlk',

    });

using second plugin :

<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>

you can get with html:

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({ 
        html: errorMsgs // error msg
    });
}
like image 37
Pradeep Avatar answered Jan 30 '26 15:01

Pradeep