validate.js 10.7 KB
/**
 * 个人中心页-账号安全验证
 * @author:wsl<shuiling.wang@yoho.cn>
 * @date: 2016/02/23
 */
var $ = require('yoho.jquery'),
    dialog = require('../common/dialog'),
    phoneRegx = require('../passport/mail-phone-regx'),
    Alert = dialog.Alert;

var $checkUser = $('.check-user'),
    $checkInput = $checkUser.find('input').not('input[type=button],input[type=hidden]'),
    canSend = true,
    stime = 60;

var sInt,
    active;

function errorInfoAction(opt, txt) {
    opt.$checkInfo.html('<div class="form-error">' + txt + '</div>');
    opt.dom.addClass('input-error');
    return false;
}

function successInfoAction(opt) {
    opt.$checkInfo.html('<div class="form-success">&nbsp;</div>');
    opt.dom.removeClass('input-error');
    return true;
}

// 身份校验
function checkForm(dom) {
    var val = dom.val(),
        len = val.length,
        $domParent = dom.parent(),
        $checkInfo = $domParent.find('.check-info'),
        inputName = dom.attr('name'),
        regular = '',
        text = '',
        opt = {
            $checkInfo: $checkInfo,
            dom: dom
        };

    $checkInfo.html('');

    if (inputName === 'password') {
        if (len === 0) {
            return errorInfoAction($checkInfo, dom, '密码不能为空!');
        } else {
            $.post('/home/account/checkpassword', {
                password: val
            }, function(data) {
                if (typeof data.code !== 'undefined' && data.code === 200) {
                    return successInfoAction(opt);
                } else {
                    return errorInfoAction(opt, '密码错误!');
                }
            });
        }
    }

    if (inputName === 'verifyCode') {
        $.post('/home/account/checkverifycode', {
            verifyCode: val
        }, function(data) {
            if (typeof data.code !== 'undefined' && data.code === 200) {
                return successInfoAction(opt);
            } else {
                return errorInfoAction(opt, '验证码错误!');
            }
        });
    }

    if (inputName === 'email') {
        regular = '([a-zA-Z0-9]+)@([a-zA-Z0-9]+)[\.]([a-zA-Z0-9]+)';

        if (val.match(regular) === null) {
            return errorInfoAction(opt, '邮箱错误!');
        } else {
            $.post('/home/account/checkemail', {
                email: val
            }, function(data) {
                if (typeof data.code !== 'undefined' && data.code === 200) {
                    return successInfoAction(opt);
                } else {
                    return errorInfoAction(opt, data.message);
                }
            });

        }
    }

    if (inputName === 'mobile') {
        regular = phoneRegx.phoneRegx;
        text = val.split('-');

        if (text.length === 1) {
            regular = val.match('^1[35847]{1}[0-9]{9}');
        } else {
            regular = regular['+' + text[0]].test(text[1]);
        }

        if (len === 0) {
            return errorInfoAction(opt, '手机号不能为空!');
        } else if (regular === null || !regular) {
            return errorInfoAction(opt, '手机号错误!');
        } else {
            $.post('/home/account/checkmobile', {
                mobile: val
            }, function(data) {
                if (typeof data.code !== 'undefined' && data.code !== 200) {
                    return errorInfoAction(opt, '手机号已经存在!');
                } else {
                    return successInfoAction(opt);
                }
            });
        }
    }

    if (inputName === 'newPwd') {
        if (len < 6 || len > 20) {
            return errorInfoAction(opt, '密码长度为6-20字符');
        } else {
            return successInfoAction(opt);
        }
    }

    if (inputName === 'confirm_password') {
        if ($('#newPwd').val() !== val) {
            return errorInfoAction(opt, '两次密码不一致!');
        } else if ($('#newPwd').val() !== '') {
            $('#newPwd').next().html('<div class="form-success">&nbsp;</div>');
            return successInfoAction(opt);
        }
    }

    if (inputName === 'code') {
        if (val !== '') {
            $.post('/home/account/checkmobilemsg', $('#pwdform').serialize(), function(data) {
                if (typeof data.code !== 'undefined' && data.code === 200) {
                    return successInfoAction($checkInfo, dom);
                } else {
                    return errorInfoAction(opt, '验证码错误!');
                }
            });
        }
    }

    return true;
}

// 校验表单
function checkAllForm() {
    var arr = [];

    $.each($checkInput, function(key, item) {
        arr.push(checkForm($(item)));
    });

    if (arr.indexOf(false) >= 0) {
        return false;
    } else {
        return true;
    }
}

// 切换验证码
function changeCode() {
    var timestamp = (new Date()).getTime();

    $('#the-code-img').attr('src', '/passport/images?len=6&time=' + timestamp);
}

// 重新发送倒计时
function code() {
    var sstring = '';

    if (stime > 0) {
        sstring = '重新发送' + stime + '秒';
        $('#sendButton').text(sstring);
        stime = stime - 1;
    } else {
        stime = 60;
        $('#sendButton').text('发送验证码');
        clearInterval(sInt);
        canSend = true;
    }
}

// 发送手机验证码
function sendcode() {
    var $mobile = $('#mobilevalue'),
        $code = $('#inputcode'),
        $mcheckInfo = $mobile.next(),
        mobileV = $mobile.val(),
        $ccheckInfo = $code.parent().find('check-info'),
        mobileObj = mobileV.split('-');

    if (mobileObj.length === 1) {
        mobileObj = mobileV.match('^1[35847]{1}[0-9]{9}');
    } else {
        mobileObj = phoneRegx.phoneRegx['+' + mobileObj[0]].test(mobileObj[1]);
    }

    if (canSend) {
        if (mobileObj === null || !mobileObj) {
            $mcheckInfo.html('<div class="form-error">手机号错误!</div>');
            $mobile.addClass('input-error');
            return false;
        }
        $.post('/home/account/sendmobilemsg', {
            mobile: mobileV
        }, function(data) {
            if (typeof data.code !== 'undefined' && data.code === 200) {
                canSend = false;
                sInt = setInterval(function() {
                    code();
                }, 1000);
                $ccheckInfo.html('');
            } else {
                $ccheckInfo.html('<div class="form-error">验证码发送失败</div>');
            }
        });
    } else {
        return false;
    }
}

// 验证完成后倒计时跳转
function toHome() {
    window.location.href = '/home/account';
}

// ajax公共处理模块
function ajaxAction(opt, flag) {
    $.post(opt.url, opt.data, function(data) {
        if (data.code === 200) {
            if (flag) {
                opt.hrefUrl += '&checkCode=' + data.data;
            }

            window.location.href = opt.hrefUrl;
        } else {
            active = new Alert(data.message);
            active.show();
            return false;
        }
    }, 'json');
}


// 提交表单
function submitForm() {
    var step = $('.progress-bar .cur').index(),
        verifyType = $('#verifyType').val(),
        curType = '',
        opt = {};

    if ($('.email').length > 0) {
        curType = 'email';
    }

    if ($('.mobile').length > 0) {
        curType = 'mobile';
    }

    if ($('.userpwd').length > 0) {
        curType = 'userpwd';
    }

    /*
     * step 0: 验证身份 1:验证第二步骤 2:验证第三步骤
     * verifyType 验证身份的状态 1:登录密码验证 2:邮箱的身份验证 3:手机的身份验证
     */
    if (step === 0) {
        if (verifyType === '1') {
            opt = {
                url: '/home/account/verifypassword',
                data: $('#pwdform').serialize(),
                hrefUrl: '/home/account/' + curType + '?step=2'
            };

            ajaxAction(opt, 'step1');

            // if (!ajaxAction(opt)) {
            //     $("input[type=reset]").trigger("click");
            // }
        } else if (verifyType === '2') {
            opt = {
                url: '/home/account/sendemail',
                data: {
                    checkType: curType,
                    email: $('#isVerifyType').html()
                },
                hrefUrl: '/home/account/sendemailsuccess?email=' + $('#isVerifyType').html() +
                        '&type=1&checkType=' + curType
            };
            ajaxAction(opt);
        } else {
            opt = {
                url: '/home/account/checkmobilemsg',
                data: {
                    email: $('#isVerifyType').html()
                },
                hrefUrl: '/home/account/' + curType + '?step=2'
            };
            ajaxAction(opt, 'step1');
        }
    } else if (step === 1) {
        if (curType === 'userpwd') {
            opt = {
                url: '/home/account/modifypwd',
                data: $('#pwdform').serialize(),
                hrefUrl: '/home/account/userpwd?step=3'
            };
            ajaxAction(opt);
        } else if (curType === 'email') {
            opt = {
                url: '/home/account/modifyemail',
                data: {
                    email: $('#email').val()
                },
                hrefUrl: '/home/account/sendemailsuccess?email=' + $('#email').val() +
                        '&type=2&checkType=email'
            };
            ajaxAction(opt);
        } else {
            opt = {
                url: '/home/account/modifymobile',
                data: {
                    mobile: $('#mobilevalue').val()
                },
                hrefUrl: '/home/account/mobile?step=3'
            };
            ajaxAction(opt);
        }
    }
}

$checkInput.blur(function() {
    checkForm($(this));
});

$('.sub-btn').on('click', function() {
    if (checkAllForm()) {
        submitForm();
    } else {
        return false;
    }
});

$('input[name=verifyCode]').keydown(function(e) {
    if (e.keyCode === 13) {
        if (checkAllForm()) {
            submitForm();
        } else {
            return false;
        }
    }
});

$('.the-code').on('click', function() {
    changeCode();
});

$('#send-mobile-code').on('click', function() {
    sendcode();
});

$(function() {
    var t = null;

    if ($('.res-info').length > 0) {
        t = setTimeout(function() {
            toHome();
        }, 5000);
    }

    changeCode();
});