<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> 表单验证</title> <style type="text/css"> <!-- body,td,th { font-size: 12px; color: #000000; } body { background-color: #CCCCCC; margin-left: 0px; margin-top: 0px; } a { font-size: 12px; color: #666600; } a:link { text-decoration: none; } a:visited { text-decoration: none; color: #000099; } a:hover { text-decoration: underline; color: #6633FF; } a:active { text-decoration: none; color: #00FF00; } --> </style> <script type="text/javascript"> function checkusername() { var myform = document.getElementById("form1"); var username = myform.username.value.length; if(username < 1||username>12) { errusername.innerHTML = "<font color='red'>用户名不符合要求</font>"; return false; }else{ errusername.innerHTML = "<font color='green'>用户名符合要求</font>"; return true; } } function checkage() { var myform = document.getElementById("form1"); var age = myform.age.value; if(age != parseInt(age)) { errage.innerHTML = "<font color='red'>年龄不符合要求</font>"; return false; }else{ errage.innerHTML = "<font color='green'>年龄符合要求</font>"; return true; } } function checkemail() { var myform = document.getElementById("form1"); var mail=https://www.jb51.net/^[A-Za-z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/; if(!mail.test(myform.email.value)) { erremail.innerHTML = "<font color='red'>email不符合要求</font>"; return false; }else{ erremail.innerHTML = "<font color='green'>email符合要求</font>"; return true; } } function checkform() { checkusername();checkage();checkemail(); if(checkusername()&&checkage()&&checkemail()) { return true; }else{ return false; } } </script> </head> <body alink="center"> <form method="post" action="ttt.jsp" onsubmit="return checkform()"> <table cellpadding="1" cellspacing="1"> <tr> <td colspan="3" ><div>请输入你的注册信息</div></td> </tr> <tr> <td ><div >请输入你的用户名:</div></td> <td><div> <input type="text" onblur="checkusername()" /> </div></td> <td><div></div></td> </tr> <tr> <td><div>请输入你的年龄:</div></td> <td><div > <label> <input type="text" onblur="checkage()"/> </label> </div></td> <td><div></div></td> </tr> <tr> <td><div >请输入你的EMAIL:</div></td> <td><div > <label> <input type="text" onblur="checkemail()" /> </label> </div></td> <td><div></div></td> </tr> <tr> <td><div> <label> <input type="submit" value="提交" /> </label> </div></td> <td><div> <label> <input type="reset" value="重置" /> </label> </div></td> <td><div></div></td> </tr> </table> </form> </body> </html>
运行效果:
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript正则表达式技巧大全》、《JavaScript表单(form)操作技巧大全》、《JavaScript数据结构与算法技巧总结》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结》