js实现的一个验证码功能,可以在前端判断验证码输入是否正确
输入的邮箱格式是否正确
验证成功后才提交action到后台
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml" > 3 <head> 4 <title>无标题页</title> 5 <style type="text/css"> 6 .code 7 { 8 <!--可以放一张背景图片更好看--> 9 background-image:url(code.jpg); 10 font-family:Arial; 11 font-style:italic; 12 color:Red; 13 border:0; 14 padding:2px 3px; 15 letter-spacing:3px; 16 font-weight:bolder; 17 } 18 .unchanged 19 { 20 border:0; 21 } 22 </style> 23 <script language="javascript" type="text/javascript"> 24 25 var code ; //在全局 定义验证码 26 function createCode() 27 { 28 code = ""; 29 var codeLength = 6;//验证码的长度 30 var checkCode = document.getElementById("checkCode"); 31 var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,‘A‘,‘B‘,‘C‘,‘D‘,‘E‘,‘F‘,‘G‘,‘H‘,‘I‘,‘J‘,‘K‘,‘L‘,‘M‘,‘N‘,‘O‘,‘P‘,‘Q‘,‘R‘,‘S‘,‘T‘,‘U‘,‘V‘,‘W‘,‘X‘,‘Y‘,‘Z‘);//所有候选组成验证码的字符,当然也可以用中文的 32 33 for(var i=0;i<codeLength;i++) 34 { 35 36 37 var charIndex = Math.floor(Math.random()*36); 38 code +=selectChar[charIndex]; 39 40 41 } 42 // alert(code); 43 if(checkCode) 44 { 45 checkCode.className="code"; 46 checkCode.value = code; 47 } 48 49 } 50 51 function validate () 52 { 53 var inputCode = document.getElementById("input1").value; 54 if(inputCode.length <=0) 55 { 56 document.getElementById("yzm").innerText="请输入验证码!"; 57 return false; 58 59 } 60 else if(inputCode != code ) 61 { 62 document.getElementById("yzm").innerText="验证码输入错误!"; 63 //alert("验证码输入错误!"); 64 createCode();//刷新验证码 65 return false; 66 } 67 else 68 { 69 var inputCode = document.getElementById("email").value; 70 if(inputCode.length <=0) 71 { 72 document.getElementById("yzm").innerText="请输入您的邮箱,方便我们联系您!"; 73 return false; 74 }else{ 75 76 //提交action 77 var f = document.forms[0]; 78 f.action=""; 79 f.submit(); 80 } 81 } 82 83 } 84 <!-- 可以控制验证是否是邮箱格式 85 function emailCheck() { 86 var objName = document.getElementById("email"); 87 var pattern = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9][email protected]([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; 88 if (!pattern.test(objName.value)) { 89 document.getElementById("yzm").innerText="请输入正确的邮箱地址!"; 90 objName.focus(); 91 document.getElementById("email").innerText=""; 92 return false; 93 } 94 document.getElementById("yzm").innerText=""; 95 return true; 96 } 97 --> 98 </script> 99 </head> 100 <body onload="createCode()"> 101 <form action="#"> 102 <input type="text" id="input1" placeholder="此项必填哦"/> 103 <input type="text" onclick="createCode()" readonly="readonly" id="checkCode" class="unchanged" style="width: 80px" /><br /> 104 <input id="Button1" onclick="validate();" type="button" value="确定" /> 105 <label id="yzm" style="color:red;margin-left:15em"></label> 106 </form> 107 </body> 108 </html>
时间: 2024-10-05 23:53:39