欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

求js代码能够将用户输入的手机号,验证,并传入后台的代码

程序员文章站 2022-04-04 20:44:55
...

前端页面如下

求js代码能够将用户输入的手机号,验证,并传入后台的代码

<p class="form-group">
    {!! Form::label('phone','新手机号',['class' => 'col-md-2 control-label']) !!}
    <p class="col-md-5">
        {!! Form::text('phone',null,['class'=>'form-control']) !!}
    </p>
    <p class="col-md-4">
        <p class="form-control-static">
        <a href="#">发送验证码</a>
        </p>
    </p>
</p>

后台发送方法位sendVerifyMessage,对应的路由为domain/send-verify-message
求js代码能够将用户输入的手机号,验证,并传入后台的代码。

回答:

需要jquery 和 jquery.cookie

var SendCode = (function($, Cookies) {
    return {
        _config : {sendObj:$('#sendCode'), mobile:$('input[name=mobile]')},
        _timer : null,
        /**
         * 初始化发化验证码类
         *
         */
        init : function(config) {
            this._initDisable();
            $.extend(this._config, config);
            
            return this;
        },
        /**
         * 异步检查手机号是否合法
         */
        AsynCheckMobile : function(url, data, successCallback, errorCallback) {
            this.doPost({ url: url, data:data, successCallback:successCallback, errorCallback:errorCallback});
        },
        /**
         *    发送验证码
         */         
        sendCode : function(url, data, successCallback, errorCallback) {
            this.doPost({ url: url, data:data, successCallback:successCallback, errorCallback:errorCallback});
        },
        /**
         * 异步交互动作
         */
        doPost : function(params) {
            if (toString.call(params.successCallback) !== "[object Function]") {
                params.successCallback = function() {};
            }
            
            if (toString.call(params.errorCallback) !== "[object Function]") {
                params.errorCallback = function() {};
            }
            
            var _this = this;
            $.ajax({
                url : params.url,
                data : params.data,
                type : 'post',
                dataType : 'json',
                success : function(result) {
                    if (result.code == 200) {
                        params.successCallback.call(_this, result);
                    } else {
                        params.errorCallback.call(_this, result);
                    }
                }
            })
        },
        checkMobile: function() {
            return /\d{11}/.test(this._config.mobile.val());
        },
        /**
         *    禁用按钮
         */
        _disableButton : function() {
            
            var TotalSeconds = 60;
            var storeState = Cookies.getJSON('state');
            storeState = storeState || {TotalSeconds:TotalSeconds, enable:false};
            Cookies.set('state', JSON.stringify(storeState), {path:''});
            this._config.sendObj.prop('disabled', true);
            var _this = this;
            this._timer = setInterval(function() {
                var _state = Cookies.getJSON('state');
                if (_state.TotalSeconds <= 0) {
                    clearInterval(_this._timer);
                    Cookies.remove('state', { path: '' });
                    _this._config.sendObj.removeAttr('disabled');
                    _this._config.sendObj.html('发送验证码');
                } else {
                    _this._config.sendObj.html(_state.TotalSeconds + '秒后发送');
                    _state.TotalSeconds -= 1;
                    Cookies.set('state', _state, {path:''})
                }
            }, 1000);
        },
        _initDisable : function() {
            var _state = Cookies.getJSON('state');
            if (_state) {
                this._disableButton();
            }
        }
    }
})(jQuery, Cookies);
   var AsynV = {
        'asynValidateCode' : function(data, successCallback, errorCallback) {
            data = data || { code:$('input[name=captcha]').val()};
            successCallback = successCallback || function() { return true;};
            errorCallback = errorCallback || function() {return false;};
            $.post('/simple/_asyn_check_code', data, function(result) {
                if (200 == result.code) {
                    (successCallback)();
                } else {
                    (errorCallback)();
                }
            }, 'json');
        }
    };
    
    SendCode.init();
    $('#sendCode').bind('click', function() {
    
        var captcha = $('input[name=captcha]').val();
        if (captcha != '') {
            AsynV.asynValidateCode({ code:captcha}, function() {
                if (SendCode.checkMobile()) {
                    SendCode.sendCode('/simple/_send_mobile_validate_code', { mobile:SendCode._config.mobile.val()}, function(result) {
                        alert(result.message);
                        this._disableButton();
                    }, function(result) {
                        alert(result.message);
                    });
                } else {
                    alert('不正确的手机号');
                }
            }, function() {
                alert('图形验证码不正确');
            });
        } else {
            alert('请先输入图形验证码');
        }
        
    });

推荐答案

HTML:

<p class="form-group">
    {!! Form::label('phone','新手机号',['class' => 'col-md-2 control-label']) !!}
    <p class="col-md-5">
        {!! Form::text('phone',null,['class'=>'form-control']) !!}
    </p>
    <p class="col-md-4">
        <p class="form-control-static">
        <a id="send-captcha" href="#">发送验证码</a>
        </p>
    </p>
</p>

JS:

<script>
    // 定义按钮btn
    var btn = $("#send-captcha");
         
    // 定义发送时间间隔(s)
    var SEND_INTERVAL = 60;
    var timeLeft = SEND_INTERVAL;
    
    /**
    * 绑定btn按钮的监听事件
    */
    var bindBtn = function(){
        btn.click(function(){
            // 需要先禁用按钮(为防止用户重复点击)
            btn.unbind('click');
            btn.attr('disabled', 'disabled');
            $.ajax({
                // ajax接口调用...
            })
            .done(function () {
                alert('发送成功');
                //成功
                timeLeft = SEND_INTERVAL;
                timeCount();                
            })
            .fail(function () {
                //失败,弹窗
                alert('发送失败');

                // ** 重要:因为发送失败,所以要恢复发送按钮的监听 **
                bindBtn();
                btn.remove('disabled');
            });
        })
    }           
    
    /**
    * 重新发送计时
    **/ 
    
    var timeCount = function() {
        window.setTimeout(function() {
            if(timeLeft > 0) {
                timeLeft -= 1;
                btn.html(timeLeft + "后重新发送");
                timeCount();
            } else {
                btn.html("重新发送");
                bindBtn();
            }
        }, 1000);
    }
</script>