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

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 = /^1[0-9]{10}$/;
            if (phone.length == 0) {
                //alert('请输入手机号码');
                $.toptip("请输入手机号码", 'error');
                return false;
            }
            if (!pattern.test(phone)) {
                //alert('请输入正确的手机号码');
                $.toptip("手机号格式错误", 'error');
                return false;
            }
            return true;
        }
        var countdown = 60;
        function settime(obj) {
            if (countdown == 0) {
                $(obj).removeAttr("disabled");
                $(obj).text("获取验证码");
                countdown = 60;
                return;
            } else {
                $(obj).attr("disabled", true);
                $(obj).text(countdown +'s'+'后重发');
                countdown--;
            }
            setTimeout(function () {
                settime(obj)
            }, 1000)
        }
</script>

 

posted @ 2017-09-04 17:27  我没有领悟  阅读(3007)  评论(0编辑  收藏  举报