JavaScript学习笔记2

表单验证

邮箱验证一般使用正则表达式:

【1】^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$

【2】/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/

在输入控件失去焦点时进行验证:

  • 失去焦点的事件为onblur
  • 获得焦点的事件为onfocus
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<link href="Untitled-1.css" rel="stylesheet" type="text/css">
</head>
<body>
<form id='form1' name="form1" action='Untitled-2.html' method="post" onSubmit="return validateForm()">
    请输入Email:<input type='text' id="emailInput" name='emailInput' class='init'></input>
    <input type='submit' value="提交" id="submit" name="submit"></input>
</form>
<script type="text/javascript">
    function validateEmail(){
        var emailInput = document.getElementById('emailInput');
        var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
        if(reg.test(emailInput.value)){
            emailInput.className = 'right';
            return true;
        }
        else{
            emailInput.className = 'wrong';
            return false;
        }
    }
    function validateForm(){
            return validateEmail();
    }
    window.onload = function(){
        document.getElementById('emailInput').addEventListener('blur',validateEmail,false);
        document.getElementById('form1').addEventListener('submit',validateForm,false);
    }

</script>
</body>
</html>

css文件下附:

@charset "utf-8";
/* CSS Document */

.init{
    border-color:#000000;
    font-size:20px;
    border-width:3px;
}

.wrong{
    border-color:#FF0000;
    font-size:20px;
    border-width:3px;   
}

.right{
    border-color:#00FF00;
    font-size:20px; 
    border-width:3px;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值