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

问题描述 投票:0回答:1

我想使用 sweet alert 作为弹出窗口,但我想确保用户在输入字段中输入一个字符串,如果这样的用户由于将其留空而未能输入某些内容,并尝试继续,则 sweet alert 应该抛出一个错误信息

<!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/[email protected]/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/[email protected]/dist/sweetalert2.all.min.js"></script> 
   </body>
</html>
javascript html sweetalert2
1个回答
0
投票

您可以使用

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");
        }
    },
})
© www.soinside.com 2019 - 2024. All rights reserved.