JS sweetalert实现输入框输入6位验证码并判断输入内容是否正确
时间: 2024-02-18 12:03:27 浏览: 30
要在SweetAlert中添加输入框并判断输入内容是否为6位验证码,可以使用SweetAlert2库提供的`Swal.fire()`方法。下面是一个示例代码:
```javascript
Swal.fire({
title: 'Please enter the verification code:',
input: 'text',
showCancelButton: true,
confirmButtonText: 'Submit',
preConfirm: (code) => {
if (!/^\d{6}$/.test(code)) {
Swal.showValidationMessage('Please enter a valid verification code')
}
else {
return code
}
}
}).then((result) => {
if (result.value) {
Swal.fire({
title: `Your verification code is ${result.value}`,
type: 'success'
})
}
})
```
这段代码将弹出一个SweetAlert对话框,要求用户输入6位验证码。如果用户输入的不是6位数字验证码,则会显示相应的错误消息。如果输入内容正确,则会显示验证码。
在`Swal.fire()`方法中,我们设置了以下选项:
- `title`:对话框标题,显示提示信息“Please enter the verification code:”;
- `input`:输入框类型,设置为`text`表示文本输入框;
- `showCancelButton`:是否显示取消按钮,设置为`true`;
- `confirmButtonText`:确认按钮的文本,设置为“Submit”;
- `preConfirm`:输入内容验证函数,如果验证通过,则返回输入的内容。如果验证不通过,则显示相应的错误消息。
在`preConfirm`函数中,我们使用正则表达式`/^\d{6}$/`来检查输入内容是否为6位数字验证码。如果不是,则显示“Please enter a valid verification code”的错误消息。如果输入内容正确,则返回输入的内容。
在`then`方法中,我们检查是否有正确的输入内容,如果有,则显示验证码。如果没有,则不做任何处理。
希望这能帮到你!