JS_登录表单验证

JS_登录表单验证

JavaScript 可用来在数据被送往服务器前对 HTML 表单中的这些输入数据进行验证。

被 JavaScript 验证的这些典型的表单数据有:

  • 用户是否已填写表单中的必填项目?
  • 用户输入的邮件地址是否合法?
  • 用户两次输入的密码是否一致?
  • 用户是否在数据域中输入了文本?
  • 这里写了几个常用的表单验证项

  • 先看效果图吧

    表单验证.jpg
  • HTML


    

欢迎注册

  • CSS

  • JavaScript
var validateData = {
    "#inputUsername": {
        validFn: validateUsername,
        failedTip: "支持中文、英文、数字、“-”、“_”的组合,4-20个字符"
    },
    "#inputPassword": {
        validFn: validatePassword,
        failedTip: "建议使用字母、数字和符号两种及以上的组合,6-20个字符"
    },
    "#confirmPassword": {
        validFn: confirmPassword,
        failedTip: "两次输入密码不符"
    },
    "#inputEmail": {
        validFn: validateEmail,
        failedTip: "请输入正确的邮箱"
    }
}

function $(selector) {
    var ele = null;
    return (ele = document.querySelectorAll(selector)).length === 1 ? ele[0] : ele;
}

function validate(value, validFn, tip) {
    this.nextElementSibling.innerHTML = "";
    this.parentNode.style.borderColor = "#ddd";
    validFn(value) ? success.call(this) : failed.call(this, tip);
}

function success() {
    // 给当前元素 , 加上class名 success;
    // alert("成功验证");
    if (/failed/.test(this.parentNode.className)) {
        this.parentNode.className = this.parentNode.className.replace("failed", "success")
    } else {
        this.parentNode.className += /success/.test(this.parentNode.className) ? "" : " success";
    }
    this.nextElementSibling.innerHTML = "";
}

function failed(tip) {
    // alert("失败验证");
    if (/success/.test(this.parentNode.className)) {
        this.parentNode.className = this.parentNode.className.replace("success", "failed")
    } else {
        this.parentNode.className += /failed/.test(this.parentNode.className) ? "" : " failed";
    }
    this.nextElementSibling.innerHTML = tip;
}

function validateUsername(value) {
    var reg = /^[\u4e00-\u9fa5a-zA-Z0-9\-_]{4,20}$/;
    return reg.test(value)
}

function validatePassword(value) {
    var passwordLevel = 0;
    var passwordLevelReg = {
        num_reg: /\d/,
        letter_reg: /[a-zA-Z]/,
        symbol_reg: /[^0-9a-zA-Z]/
    }
    for (var attr in passwordLevelReg) {
        if (passwordLevelReg[attr].test(value)) {
            passwordLevel++;
        }
    }
    return passwordLevel >= 2 && /[\s\S]{6,20}/.test(value);
}

function confirmPassword(value) {
    var password = inputPassword.value;
    if (password === "") {
        return false;
    }
    // 如果password不为空;
    return value === password
}

function validateEmail(value) {
    var reg = /^\w{4,20}@[0-9a-zA-Z]{2,20}\.(com|cn|net)$/;
    return reg.test(value)
}

function handlerBlur(validFn, tip) {
    return function() {
        // 取值 ;
        var value = this.value;
        validate.call(this, value, validFn, tip)
    }
}

for (var attr in validateData) {
    $(attr).addEventListener("blur", handlerBlur(validateData[attr].validFn, validateData[attr].failedTip));
}

你可能感兴趣的:(JS_登录表单验证)