javascript 如果输入字段为空并且用户尝试继续,如何使用sweetalert2抛出错误

v09wglhw  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(157)

我想使用甜蜜的警报作为一个弹出窗口,但我想确保用户输入一个字符串到输入字段,如果这样的用户未能通过留空输入的东西,并试图继续,甜蜜的警报应该抛出一个错误消息

<!DOCTYPE html>    
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" 
         />
      <title>Document</title>
      <link
         href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.1/dist/sweetalert2.min.css"
         rel="stylesheet"
         />
   </head>
   <body onload="check()">
      <script>
         if (!localStorage.adminDetails) {
               let adminName = []
               if (localStorage.adminDetails) {
                 adminName = JSON.parse(localStorage.getItem("adminDetails"));
               }
               check = () => {
                 Swal.fire({
                   title: `What's Your Name`,
                   input: "text",
                   allowOutsideClick: false,
                   inputAttributes: {
                     autocapitalize: "on",
                   },
                   showCancelButton: false,
                   confirmButtonText: "Save changes",
                   showLoaderOnConfirm: true,
                 }).then((result) => {
                   if (result.isConfirmed) {
                     Swal.fire("Good job!", `Wlcome ${result.value}`, "success");
                   } else if (result.value === "" || result.value === undefined) {
                     text = "Never";
                   }
         
                   let theAdminName = {
                     adminFName: result.value,
                   };
                   adminName.push(theAdminName);
                   localStorage.setItem("adminDetails", JSON.stringify(adminName));
                   adminName.map((eachAdmin, index) => {
                     localStorage.setItem("currentAdminIndex", index);
                   });
                 });
               }; }
             
      </script>
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.1/dist/sweetalert2.all.min.js"></script> 
   </body>
</html>
2ledvvac

2ledvvac1#

您可以使用preConfirm选项来显示验证错误消息:

Swal.fire({
    title: `What's Your Name`,
    input: "text",
    allowOutsideClick: false,
    inputAttributes: {
        autocapitalize: "on",
    },
    showCancelButton: false,
    confirmButtonText: "Save changes",
    showLoaderOnConfirm: true,
    preConfirm: (name) => {
        if (!name || name.trim() === "") {
            Swal.showValidationMessage("Please enter your name");
        }
    },
})

相关问题