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



我想使用甜蜜警报作为弹出窗口,但我想确保用户在输入字段中输入字符串如果用户未能输入内容,留下空白,并试图继续,甜蜜警报应该抛出错误消息

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

您可以使用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");
}
},
})

相关内容

  • 没有找到相关文章

最新更新