1. QQ号:<input type="text" id="txtQQ"><span></span><br>
    2. 邮箱:<input type="text" id="txtEMail"><span></span><br>
    3. 手机:<input type="text" id="txtPhone"><span></span><br>
    4. 生日:<input type="text" id="txtBirthday"><span></span><br>
    5. 姓名:<input type="text" id="txtName"><span></span><br>
    6. //1.获取页面所有的inputs
    7. var inputs = my$byTagName("input");
    8. //2.遍历inputs绑定事件
    9. for(var i=0;i<inputs.length;i++){
    10. inputs[i].onblur = function(){
    11. checkCorrect(this);
    12. }
    13. }
    14. //3.每次文本框失去焦点时候确定文本框对应的正则以及提示
    15. function checkCorrect(ele){
    16. var reg = null;
    17. var tip = null;
    18. //检验QQ
    19. if(ele.getAttribute("name") == "qq") {
    20. reg = /^[1-9]\d{4,10}$/;
    21. tip = "请输入正确的QQ号码";
    22. }
    23. //校验email
    24. else if(ele.getAttribute("name") == "email"){
    25. reg = /^\w+@\w+\.\w+(\.\w+)?$/;
    26. tip = "请输入正确的email";
    27. }
    28. else if(ele.getAttribute("name") == "phone"){
    29. reg = /^1[34578]\d{9}$/;
    30. tip = "请输入正确的手机号码";
    31. }
    32. else if(ele.getAttribute("name") == "birthday"){
    33. reg = /^((\d{4})-(\d{2})-(\d{2}))$/;
    34. tip = "请输入正确的生日";
    35. }
    36. else if(ele.getAttribute("name") == "name"){
    37. reg = /^\w{2,}$/;
    38. tip = "请输入正确的名字";
    39. }
    40. //真正去进行校验
    41. doCheck(ele,reg,tip);
    42. }
    43. //正则的校验
    44. function doCheck(element, reg, tip){
    45. //获取当前input的下一个兄弟元素
    46. var span = element.nextElementSibling;
    47. //如果正则校验通过,则输入正确
    48. if(reg.test(element.value)){
    49. span.style.color = "green";
    50. setInnerText(span,"输入正确");
    51. }
    52. else{
    53. span.style.color = "red";
    54. setInnerText(span,tip);
    55. }
    56. }

    test.gif