如何使用换行符在 SweetAlert 上输出 CodeIgniter 验证错误消息?

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

在控制器文件中:

这就是我json_encode查看验证错误的方式:

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

在查看文件中:

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
    });
}

SweetAlert 上的输出:

这是 Name1 字段错误消息。<br/>这是 Name2 字段错误消息。<br/>这是 Name3 字段错误消息。

我自己找到了解决办法。 :D

只需使用“\n”代替“<br>”!

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

案例https://sweetalert.js.org/ VS https://sweetalert2.github.io/

对于:https://sweetalert.js.org/

如文档所述:html 不再使用。

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

改为使用内容对象。

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

对于:https://sweetalert2.github.io/

如果您正在使用此 SweetAlert2 插件,请点击此处

https://sweetalert2.github.io/

您可以通过 html

获得您想要的结果
swal({
        title: "<i>Title</i>", 
        html: 'A custom message.</br> jkldfjkjdklfjlk',

    });

使用第二个插件:

<script src="https://unpkg.com/sweetalert2@7.19.1/dist/sweetalert2.all.js"></script>

你可以用 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
    });
}