简单表单验证

简单的表单验证

index.js

$(document).ready(function() {
    var check = {
        regs: {
            name: /\b(^['A-Za-z0-9]{4,20}$)\b/,
            phone: /^1[3,4,5,6,7,8,9]{1}[0-9]{9}$/,
            activecode: /^[\u4E00-\u9FA5A-Za-z0-9]{6,20}$/,
            captcha: /^\d{6}$/
        },
        wait: 40,
        get: {
            name: $("input[name='name']"),
            cphone: $("input[name='cphone']"),
            activecode: $("input[name='active-code']"),
            captcha: $("input[name='captcha']")
        },
        checkblur: function(obj, reg, msg, msg2) {
            if ($(obj).val() == '') {
                $(obj).siblings().addClass("show");
                $(obj).siblings().text(msg);
                $(obj).removeClass("border-green");
                $(obj).addClass("border-red");
            } else if (!reg.test($(obj).val())) {
                $(obj).siblings().addClass("show");
                $(obj).siblings().text(msg2);
                $(obj).removeClass("border-green");
                $(obj).addClass("border-red");
            } else {
                $(obj).removeClass("border-green");
            }
        },
        checkfoucs: function(obj, reg) {
            $(obj).siblings().removeClass("show");
            $(obj).removeClass("border-red");
            if (reg.test($(obj).val())) {
                $(obj).addClass("border-green");
            } else {
                $(obj).removeClass("border-green");
            }
        },
        checksubmit: function(id, reg, msg, msg2) {
            if ($("input[name='" + id + "']").val() == '') {
                $("input[name='" + id + "']").siblings().addClass("show");
                $("input[name='" + id + "']").siblings().text(msg);
                $("input[name='" + id + "']").addClass("border-red");
                return;
            }
            if (!reg.test($("input[name='" + id + "']").val())) {
                $("input[name='" + id + "']").siblings().addClass("show");
                $("input[name='" + id + "']").siblings().text(msg2);
                $("input[name='" + id + "']").addClass("border-red");
                return;
            }

        },
        timer: function(obj) {
            if (check.wait == 0) {
                obj.removeAttribute("disabled");
                obj.value = "获取验证码";
                check.wait = 40;
            } else {
                obj.setAttribute("disabled", true);
                obj.value = "重新发送 " + check.wait + "S";
                check.wait--;
                setTimeout(function() {
                    check.timer(obj);
                },
                1000)
            }
        }
    }
    // Check if the form loses focus
    $("input:not('[type='button']')").on("blur",
    function() {
        switch ($(this).attr("name")) {
        case "name":
            check.checkblur(this, check.regs.name, "姓名不能为空", "请输入正确名字");
            break;
        case "cphone":
            check.checkblur(this, check.regs.phone, "手机不能为空", "请输入正确手机号");
            break;
        case "active-code":
            check.checkblur(this, check.regs.activecode, "激活码不能为空", "请输入正确激活码");
            break;
        case "captcha":
            check.checkblur(this, check.regs.captcha, "验证码不能为空", "请输入正确验证码");
            break;

        }
    });
    // Check if the form gets focus
    $("input:not('[type='button']')").on("focus",
    function() {
        switch ($(this).attr("name")) {
        case "name":
            check.checkfoucs(this, check.regs.name);
            break;
        case "cphone":
            check.checkfoucs(this, check.regs.phone);
            break;
        case "active-code":
            check.checkfoucs(this, check.regs.activecode);
            break;
        case "captcha":
            check.checkfoucs(this, check.regs.captcha);
            break;
        }
    });

    // Check when the form submit
    $(".form-submit").click(function() {
        if (check.regs.name.test(check.get.name.val()) && check.regs.phone.test(check.get.cphone.val()) && check.regs.activecode.test(check.get.activecode.val()) && check.regs.captcha.test(check.get.captcha.val())) {
            $(this).attr("value", "");
            $(".loading").css("display", "block");
            setTimeout(function() {
                window.location.href = "https://www.baidu.com";
            },
            2000);

        } else {
            check.checksubmit("name", check.regs.name, "姓名不能为空", "请输入正确名字");
            check.checksubmit("cphone", check.regs.phone, "手机不能为空", "请输入正确手机号");
            check.checksubmit("active-code", check.regs.activecode, "激活码不能为空", "请输入正确激活码");
            check.checksubmit("captcha", check.regs.captcha, "验证码不能为空", "请输入正确验证码");

        }
    });
    // Check when obtaining the verification code
    $(".captcha-btn").click(function() {
        if (check.get.cphone.val() != '' && check.regs.phone.test(check.get.cphone.val()) && check.get.activecode.val() != '' && check.regs.activecode.test(check.get.activecode.val())) {
            check.timer(this);
        } else {
            check.checksubmit("cphone", check.regs.phone, "手机不能为空", "请输入正确手机号");
            check.checksubmit("active-code", check.regs.activecode, "激活码不能为空", "请输入正确激活码");
        }
    });
    // dialog alert
    $(".dialog-alert-del").on("click",
    function() {
        $(".dialog-alert").css("display", "none");
    });
});

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="tutorabc-form">
        <div class="form-wrap">
            <!-- form start -->
            <div class="form-card">
                <form>
                    <div class="form-items">
                        <div class="item">
                            <input name="name" type="text" placeholder="姓名">
                            <p class="error-msg"></p>
                        </div>
                        <div class="item">
                            <input name="cphone" type="text" placeholder="手机">
                            <p class="error-msg"></p>
                        </div>
                        <div class="item">
                            <input name="active-code" type="text" placeholder="激活码">
                            <p class="error-msg"></p>
                        </div>
                        <div class="item item-captcha">
                            <div class="item-captcha-text">
                                <input name="captcha" type="text" placeholder="验证码">
                                <p class="error-msg captcha-error"></p>
                            </div>
                            <div class="item-captcha-btn">
                                <input name="captcha-btn" class="btn captcha-btn" type="button" value="发送验证码">
                            </div>
                        </div>
                        <div class="item">
                            <input name="submit" class="btn form-submit" type="button" value="提交">
                            <div class="loading">
                                <img src="./img/loading.gif" alt="">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <!-- form end -->
            <!-- dialog-alert start -->
            <div class="dialog-alert">
                <div class="dialog-alert-bg"></div>
                <div class="dialog-alert-wrap">
                    <div class="dialog-alert-top">
                        <p>提示</p>
                        <span class="dialog-alert-del" title="关闭"></span>
                    </div>
                    <div class="dialog-alert-content">
                        <p>
                            您的信息有错
                        </p>
                    </div>
                    <div class="dialog-alert-bottom">
                        <div class="dialog-alert-del alert-bottom-btn">确定</div>
                    </div>
                </div>
            </div>
            <!-- dialog-alert end -->
        </div>
    </div>
    <script src="js/jquery.min.js"></script>
    <script src="js/index.js"></script>
</body>

</html>

style.css

body,
button,
dd,
div,
dl,
dt,
form,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
input,
li,
ol,
p,
td,
textarea,
th,
ul {
    margin: 0;
    padding: 0;
}

ul {
    list-style-type: none;
}

a {
    text-decoration: none;
}

::-webkit-input-placeholder {
    color: #999;
}

.error-msg {
    display: none;
    position: absolute;
    top: 24%;
    right: 12px;
    color: #f74c4c;
    font-size: 14px;
    text-align: right;
}

.captcha-error {
    right: 110px;
}

.show {
    display: block;
}

.form-wrap {
    max-width: 1000px;
    margin: 0 auto;
}

.form-card {
    display: inline-block;
    padding: 50px;
    border-radius: 4px;
    background-color: #fff;
    -webkit-box-shadow: 0 4px 6px 0 rgba(0, 0, 0, .2);
    box-shadow: 0 4px 6px 0 rgba(0, 0, 0, .2);
}

.form-item {
    width: 240px
}

.form-items .item {
    width: 100%;
    margin-bottom: 30px;
    position: relative;
}

.form-items .item:nth-child(4) {
    position: relative;
}

.form-items input {
    box-sizing: border-box;
    padding: 12px 0 12px 10px;
    background: #fff;
    border: 1px solid #dcdcdc;
    width: 100%;
    border-radius: 5px;
    color: #484848;
    outline: none;

}

.form-items input.border-red {
    border: 1px solid #f74c4c;
}

.form-items input.border-green {
    border: 1px solid green;
}

.form-items .item-captcha {
    font-size: 0;
}

.form-items .item-captcha .item-captcha-text {
    display: inline-block;
    font-size: 14px;
    width: 60%;
    margin-right: 5%;
}

.form-items .item-captcha .item-captcha-btn {
    display: inline-block;
    font-size: 14px;
    width: 35%;

}

.form-items input.btn {
    padding: 12px 0 12px 0;
    background: #f74c4c;
    border: none;
    color: #fff;
    cursor: pointer;
    transition: all 0.2s;
}

.form-items .item-captcha-btn .captcha-btn {
    width: 90px;
}

.form-items input.btn:hover {
    background: #f11313;
}

.form-items .loading {
    display: none;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 50%;
    margin-left: -14px;
    width: 28px;
}

.form-items .loading img {
    width: 100%;
}

.tutorabc-form .dialog-alert {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    z-index: 1;
}
.tutorabc-form .dialog-alert-bg{
    width: 100%;
    height: 100%;
    background: #000;
    filter: alpha(opacity=50);
    opacity: .5;
}
.tutorabc-form .dialog-alert-wrap{
    max-width: 580px;
    position: absolute;
    left: 50%;
    top: 15%;
    margin-left: -290px;
    background: #fff;
    border-radius: 5px;
    width: 100%;
}
.tutorabc-form .dialog-alert-top{
    position: relative;
    height: 50px;
    line-height: 50px;
    border-bottom: 1px solid #EDEDED;
    padding-left: 30px;
}
.tutorabc-form .dialog-alert-top p{
    color: #444;
    font-size: 16px;
}
.tutorabc-form .dialog-alert-top .dialog-alert-del{
    display: block;
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    width: 40px;
    height: 40px;
    background: url("../img/tiny-delete.png") no-repeat center center;
}
.tutorabc-form .dialog-alert-content{
    box-sizing: border-box;
    width: 100%;
    padding: 20px 30px 40px 50px;
    border-bottom: 1px solid #EDEDED;
}
.tutorabc-form .dialog-alert-bottom{
    box-sizing: border-box;
    padding: 36px 0;
    background: #fafafa;          
    position: relative;
    width: 100%;
}
.tutorabc-form .dialog-alert-bottom .alert-bottom-btn{
    position: absolute;
    right: 30px;
    top: 50%;
    margin-top: -18px;
    width: 70px;
    height: 36px;
    line-height: 37px;
    background-color: #F34D37;
    text-align: center;
    border-radius: 5px;
    color: #fff;
    font-size: 16px;
    cursor: pointer;
}

如图:
在这里插入图片描述在这里插入图片描述


简单表单字符验证

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>task29</title>
</head>
<body>
	<div id="content">
		<label>名称 <input id="txt" type="text"  autofocus="autofocus" /></label>
		<input type="button" id="submit" value="验证">
	</div>
	<p id="mes">必填,长度为4~16个字符</p>
</body>
</html>
var submitDom = document.getElementById("submit");
var textDom = document.getElementById("txt");
var mesDom = document.getElementById("mes")

function test() {
	var num = 0;
	var name = textDom.value;
	num = getLength(name)
	if (num == 0) {
		mesDom.innerHTML= '姓名不能为空';
		mesDom.className = 'error';
	} else if (num >= 4 && num <=16) {
		mesDom.innerHTML = '符合规范';
		mesDom.className = 'right';

	} else {
		mesDom.innerHTML = '输入不符合规范';
		mesDom.className = 'error';
	}
}

function getLength(str) {
	var len = 0;
	for( var i = 0; i < str.length; i++) {
		charCode = str.charCodeAt(i)
		if(charCode >-1 && charCode <129)
			len += 1;
		else
			len += 2;
	}
	return len;
}
addEvent(submitDom,"click",test);

function addEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler);
	}else if (element.attachEvent) {
		element.attachEvent("on" + type, handler);
	}else {
		element["on" +type] = handler;
	}
}

表单简单验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单内容</title>
    <style>
        .wrong{
            background:#fff;
            font-weight:bold;
            border:1px solid red;
        }
        .right{
            background:#fff;
            font-weight:bold;
            border:1px solid forestgreen;
        }
        .smallMsg{
            font-size:12px;
        }
    </style>
    <script src="formValidate.js"></script>
</head>
<body>
<form action="yanzheng.html" method="post">
    请输入你的邮箱:<input type="text" id="email" name="email" value="">
    <span id="emailMsg" class="smallMsg"></span><br>
    <button type="submit">显示邮箱地址</button>
    <br>
    请输入你的密码:<input type="password" name="pwd" id="pwd" value="">
    <span id="pwdMsg" class="smallMsg"></span><br>
    确认密码:<input type="password" name="conf" id="conf" value="">
    <span id="confMsg" class="smallMsg"></span><br>
    <!--单选钮-->
    请选择你最喜欢的运动:
    <input type="radio" name="sport" id="sport1" value="网球">网球&nbsp;
    <input type="radio" name="sport" id="sport2" value="羽毛球">羽毛球&nbsp;
    <input type="radio" name="sport" id="sport3" value="足球">足球<br>
    <button type="submit" name="sportButton" id="sport">显示所选运动</button>
    <br>

    <!--复选框-->
    请选择你的课程:
    <input type="checkbox" value="语文" name="course">语文&nbsp;
    <input type="checkbox" value="数学" name="course">数学&nbsp;
    <input type="checkbox" value="英语" name="course">英语&nbsp;
    <input type="checkbox" value="物理" name="course">物理<br>
    <input type="checkbox" value="全选" name="courseAll" id="courseAll"> 全选
    <button type="submit" name="manyCheck" id="course">显示所选课程</button>
    <br>
    <!--下拉列表框-->
    你的家乡:<select name="city" id="city">
    <option value="北京">北京</option>
    <option value="上海">上海</option>
    <option value="沈阳">沈阳</option>
</select><br>

    <!--文本域-->
    描述:<textarea id="note" name="note" cols="50" rows="10">hello!</textarea><br>
    <span id="noteMsg" class="smallMsg"></span><br>
    <button type="submit" name="textArea" id="textArea">保存</button>
    <br>
    <!--确认框-->
    <a href="xxx" onclick="return deleteConfirm()">删除邮件</a><br>
    <!--用户输入框-->
    <a href="888" onclick="return usePrompt()">提示</a>

    <!--重定向-->
    <select id="url" name="url" onchange="go(this.value)">
        <option >===请选择要显示的页面===</option>
        <option value="yanzheng.html">SHOW</option>
        <option value="http://www.baidu.com">BAIDU</option>
    </select>
</form>
</body>
</html>

formValidate.js

// var valueForm = document.getElementById("username");
//            alert("内容:" + valueForm.value);  获得表单内容
//验证表单,用正则,需要开始和结束标记  /^正则$/.test(要检测的数据)

window.onload = function(){
    document.getElementById("pwd").addEventListener("blur",validatePwd,false);
    document.getElementById("conf").addEventListener("blur",validateConf,false);
    document.getElementById("email").addEventListener("blur",validateE,false);
    document.getElementById("sport").addEventListener("click",paraSingle,false);
    document.getElementById("course").addEventListener("click",paraManyCheck,false);
    document.getElementById("courseAll").addEventListener("click",paraSelectAllCheck,false);
    document.getElementById("city").addEventListener("change",paraSelectBox,false);
    document.getElementById("note").addEventListener("keypress",paraTextArea,false);
    document.getElementById("note").addEventListener("keydown",paraTextArea,false);
};
//验证邮箱格式
function validateEmail(objName){
    var objElement = document.getElementById(objName);
    var msgElement = document.getElementById(objName + "Msg");
    if(/^\w+@\w+\.\w+$/.test(objElement.value)){
        objElement.className = "right";
        msgElement.innerHTML = "邮箱输入正确!";
        msgElement.style.color = "green";
        return true;
    }else{
        objElement.className = "wrong";
        msgElement.innerHTML = "邮箱格式错误!";
        msgElement.style.color = "red";
        return false;
    }
}
function validateE(){
    return validateEmail("email");
}
//密码和确认密码是否一致


function validateEmpty(elementName){
    var objElement = document.getElementById(elementName);
    var msgElement = document.getElementById(elementName + "Msg");
    if(objElement.value != ""){
        objElement.className = "right";
        msgElement.style.color = "green";
        msgElement.innerHTML = "正确!";
        return true;
    }else{
        objElement.className = "wrong";
        msgElement.innerHTML = "请输入密码!";
        msgElement.style.color = "red";
        return false;
    }
}
function validateRepeat(orgName,tarName){
    var orgElement = document.getElementById(orgName);
    var tarElement = document.getElementById(tarName);
    var msgElement = document.getElementById(tarName + "Msg");
    if(orgElement.value == tarElement.value){
        msgElement.style.color = "green";
        msgElement.innerHTML = "与初次密码一致!";
        tarElement.className = "right";
        return true;
    }else{
        tarElement.className = "wrong";
        msgElement.innerHTML = "与初次密码不一致,请重新输入!";
        msgElement.style.color = "red";
        return false;
    }
}
function validatePwd(){
    return validateEmpty("pwd");
}
function validateConf(){
    if(validateEmpty("conf")){
        return validateRepeat("pwd","conf");
    }
    return false;
}

// 单选框
function singleCheck(objName){
    var single = document.getElementsByName(objName);
    for(var i = 0;i < single.length;i ++){
        if(single[i].checked){
            alert("最喜欢的运动是:" + single[i].value);
        }
    }
}
function paraSingle(){
    return singleCheck("sport");
}

// 复选框
function manyCheck(objName){
    var manyCheckElement = document.getElementsByName(objName);
    var str = "所选课程:";
    for(var i = 0;i < manyCheckElement.length;i ++){
        if(manyCheckElement[i].checked){
            str += manyCheckElement[i].value + "、";
        }
    }
    alert(str);
}
function selectAllCheck(objName,objId){
    var allCheck = document.getElementsByName(objName);
    for(var i = 0;i < allCheck.length;i ++){
        allCheck[i].checked = document.getElementById(objId).checked;
    }
}
function paraSelectAllCheck(){
    return selectAllCheck("course","courseAll");
}
function paraManyCheck(){
    return manyCheck("course");
}

// 下拉列表框
function selectBox(objId){
    var objElement = document.getElementById(objId);
    alert("你的家乡:" + objElement.value);
}
function paraSelectBox(){
    return selectBox("city");
}

//文本域
function textArea(objId,submitId){
    var objElement = document.getElementById(objId);
    var msgElement = document.getElementById(objId + "Msg");
    var len = objElement.value.length;
    var submitElement = document.getElementById(submitId);
    if(len <= 10){
        msgElement.innerHTML = "您还可以输入:" + (10 - len) + "个字";
        submitElement.disabled = "";
    }else{
        msgElement.innerHTML = "您输入的字数超过限制!";
        msgElement.style.color = "red";
        submitElement.disabled = true;
    }
}
function paraTextArea(){
    return textArea("note","textArea");
}

// 警告框
function deleteConfirm(){
    return window.confirm("确定删除邮件吗?");
}
//用户输入框
function usePrompt(){
    var str = window.prompt("请输入你的名字:","姓名是:");
    document.write(str);
}
// 弹框Open
window.open("yanzheng.html","AD页","width=200;height:10;scrollBars=yes;resizeable=no");
// 重定向location
function go(url){
    window.location = url;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值