<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{margin: 0;padding: 0;} ul{list-style:none;} ul li{margin-top: 10px;} .mo{font-size:14px;color:#CCC;background:url('images/mo.gif') no-repeat;padding-left:20px;margin-left: 20px;} .ok{font-size:14px;color:green;background:url('images/ok.gif') no-repeat;padding-left:20px;margin-left: 20px;} .no{font-size:14px;color:red;background:url('images/no.gif') no-repeat;padding-left:20px;margin-left: 20px;} </style> </head> <body> <form action="1.php"> <ul> <li>账户:<input id="userName" type="text"><span id="userInfo"></span></li> <li>年龄:<input id="age" type="text"><span id="ageInfo"></span></li> <li>邮箱:<input id="email" type="text"><span id="emailInfo"></span></li> <li><input type="submit" value="提交"></li> </ul> </form> <script> // 获取账户 inpput 对象 var User = document.getElementById('userName'); var userInfo = document.getElementById('userInfo'); // 账户获取焦点 User.onfocus = function(){ userInfo.className = 'mo'; userInfo.innerHTML = '不以数字开头的数字字母下划线,4到10'; } // 账户失去焦点 验证 User.onblur = function(){ // 用正则验证用户的信息 if(User.value.match(/^[A-z][0-9A-z_]{3,9}$/)){ userInfo.className = 'ok'; userInfo.innerHTML = '输入正确'; }else{ userInfo.className = 'no'; userInfo.innerHTML = '格式不正确'; } } // 获取年龄 inpput 对象 var Age = document.getElementById('age'); var ageInfo = document.getElementById('ageInfo'); // 年龄获取焦点 Age.onfocus = function(){ ageInfo.className = 'mo'; ageInfo.innerHTML = '必须是0到150的数字 '; } // 年龄失去焦点 验证 Age.onblur = function(){ // 用正则验证用户的信息 if(Age.value.match(/^d+$/) && Age.value>0 && Age.value<=150){ ageInfo.className = 'ok'; ageInfo.innerHTML = '输入正确'; }else{ ageInfo.className = 'no'; ageInfo.innerHTML = '格式不正确'; } } // 获取邮箱 inpput 对象 var Email = document.getElementById('email'); var emailInfo = document.getElementById('emailInfo'); // 年龄获取焦点 Email.onfocus = function(){ emailInfo.className = 'mo'; emailInfo.innerHTML = '请输入正确的邮箱格式'; } // 年龄失去焦点 验证 Email.onblur = function(){ // 用正则验证用户的信息 if(Email.value.match(/^[A-z0-9_]+@[A-z0-9]+.[A-z]+$/)){ emailInfo.className = 'ok'; emailInfo.innerHTML = '输入正确'; }else{ emailInfo.className = 'no'; emailInfo.innerHTML = '格式不正确'; } } </script> </body> </html>