手机号码和验证码: 要求:单击发送验证码时,判断手机号格式是否正确(手机号必须是11位的纯数字且必须以13或者15开头) 如果格式正确 ,发送验证码按钮显示倒计时(5秒) 如果格式错误,弹出警示框'手机号格式错误'
时间: 2024-02-25 17:56:58 浏览: 58
这个要求可以通过以下的代码来实现:
```html
<!-- HTML -->
<input type="tel" id="phone-number-input" placeholder="请输入手机号">
<button type="button" id="send-verification-code-button" onclick="sendVerificationCode()">发送验证码</button>
```
```javascript
// JavaScript
function sendVerificationCode() {
const phoneNumberInput = document.getElementById('phone-number-input');
const phoneNumber = phoneNumberInput.value.trim();
const phoneNumberRegex = /^1[3|5]\d{9}$/; // 以13或15开头的11位数字
if (!phoneNumberRegex.test(phoneNumber)) {
alert('手机号格式错误');
return;
}
// 发送验证码的逻辑,这里简化为倒计时5秒
const sendVerificationCodeButton = document.getElementById('send-verification-code-button');
sendVerificationCodeButton.disabled = true;
let remainingSeconds = 5;
const intervalId = setInterval(() => {
remainingSeconds--;
if (remainingSeconds <= 0) {
sendVerificationCodeButton.innerText = '发送验证码';
sendVerificationCodeButton.disabled = false;
clearInterval(intervalId);
} else {
sendVerificationCodeButton.innerText = `重新发送(${remainingSeconds}s)`;
}
}, 1000);
}
```
这段代码中,我们使用了正则表达式来验证手机号格式是否正确,如果不正确则弹出警示框。如果格式正确,则让发送验证码的按钮显示倒计时,并在5秒后让按钮恢复到可用状态。