代码之家  ›  专栏  ›  技术社区  ›  Pasindu Jayanath

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

  •  3
  • Pasindu Jayanath  · 技术社区  · 6 年前

    在控制器文件中:

    以下是我如何对验证错误进行json\U编码以查看:

    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字段错误消息。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Pasindu Jayanath    6 年前

    我自己找到了解决方案:D

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

    errorMsgs += res.errors.name1 ? res.errors.name1 + "\n" : "";
    
        2
  •  3
  •   Pradeep    6 年前

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

    适用于: https://sweetalert.js.org/

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

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

    而是使用content对象。

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