手机验证 发送验证码倒计时js

时间:2021-09-09 15:38:21

html:

<input name="Tel" class="weui-input" type="tel" placeholder="请输入手机号">
<button type="button" class="weui-vcode-btn" onclick="getCode(this)">获取验证码</button>

js:

<script>
/*获取验证码*/
function getCode(obj) {
if (checkPhone()) {//验证手机号码
$.ajax({
type: "POST",
url: '@Url.Action("SendVerifyCode", "Account")',
data: { Tel: $("input[name='Tel']").val() },
success: function (result) {
if (result.Success) { }
else {
$.toptip(result.ErrorMessage, 'error');
}
},
error: function (result) {
$.toptip('未知异常导致请求失败,请重试.', 'error');
}
});
settime(obj); //倒计时
}
else {
$("input[name='Tel']").focus();
return;
}
}
//验证手机号码
function checkPhone() {
var phone = $("input[name='Tel']").val();
var pattern = /^[-]{}$/;
if (phone.length == ) {
//alert('请输入手机号码');
$.toptip("请输入手机号码", 'error');
return false;
}
if (!pattern.test(phone)) {
//alert('请输入正确的手机号码');
$.toptip("手机号格式错误", 'error');
return false;
}
return true;
}
var countdown = ;
function settime(obj) {
if (countdown == ) {
$(obj).removeAttr("disabled");
$(obj).text("获取验证码");
countdown = ;
return;
} else {
$(obj).attr("disabled", true);
$(obj).text(countdown +'s'+'后重发');
countdown--;
}
setTimeout(function () {
settime(obj)
}, )
}
</script>