SweetAlert2多输入模态框如何实现异步校验并正确获取输入值
问题根因
你的代码同时混用了await和.then()两种异步处理逻辑,const {value: feedback} = ...的赋值操作需要等swal.fire的整个异步流程(包括后续的.then()回调)执行完毕才会完成,因此.then()回调中访问feedback时该变量尚未初始化,自然会抛出错误。
解决方案
你可以直接使用preConfirm钩子实现提交前校验,校验不通过时模态框不会关闭,用户可以直接修正输入内容,完全匹配你的需求,同时去掉await和.then()混用的写法即可,完整修正代码如下:
jQuery('body').on('click', '#feedback', async function () { const swalResult = await swal.fire({ title: 'Send us your feedback!', showCancelButton: true, confirmButtonText: 'Submit', customClass: { content: 'full-width' }, html: '<input id="ratingValue" type="text" placeholder="评分" />' + '<input id="topicValue" type="text" placeholder="反馈主题" />' + '<input id="comment" type="text" placeholder="补充说明" />', preConfirm: () => { const rating = jQuery('#ratingValue').val().trim() const topic = jQuery('#topicValue').val().trim() const comment = jQuery('#comment').val().trim() // 提交前校验逻辑 if (!rating) { Swal.showValidationMessage('请填写评分') return false } if (!topic) { Swal.showValidationMessage('请填写反馈主题') return false } // 校验通过返回表单数据 return { rating: rating, topic: topic, comment: comment } } }) // 仅当用户点击提交按钮且校验通过时执行后续逻辑 if (swalResult.isConfirmed) { const feedback = swalResult.value console.log(JSON.stringify(feedback)) Swal.fire('Submitted!', '', 'success') // 此处可添加提交数据到后端的逻辑 } })
改动说明
- 移除了
await与.then()混用的异步逻辑冲突写法,直接通过await接收SweetAlert2返回的完整结果对象,避免变量作用域问题 - 所有输入校验逻辑放在
preConfirm钩子中,校验不通过时调用Swal.showValidationMessage()展示错误提示,模态框保持打开状态,用户可直接修改输入内容后重新提交 - 通过
swalResult.isConfirmed判断用户是否完成提交操作,确认后再处理返回的表单数据即可
内容的提问来源于stack exchange,提问作者mikes001
相关产品推荐
相关产品推荐

