Search code examples
javascripthtmlsweetalert2

How to throw an error with sweetalert2 if the input field is empty and user try continue


I want to use sweet alert as a pop up but I want to make sure that user enter a string into the input field and if such user failed to enter something by leaving it blank, and try to continue, the sweet alert should throw an error message

<!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>

Solution

  • You can use preConfirm option to show validation error message:

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