用javascript写的表单验证

原创
2014/07/30 09:57
阅读数 121

用javascript写的表单验证,可以用网站的前后台的登陆,大家可以给提点意见。这是以前做项目的时候写的

 


  
  
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
  2. <html> 
  3. <head> 
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  5. <title>验证表单</title> 
  6. <script language="JavaScript"> 
  7. function check(){  
  8. var user = document.getElementById("username").value;  
  9. var pass = document.getElementById("pass").value;  
  10. var rpass = document.getElementById("rpass").value;  
  11. var cardnum = document.getElementById("cardnum").value;  
  12. var email = document.getElementById("email").value;  
  13.  
  14. //用户名只能由字母、数字、下划线组成,其它字符一律过滤,这样也确保了安全性,  
  15. //正则表达式的意思是,当输入0-9、a-z、A-Z、_以外的任何一个或者多个字符时则提示错误  
  16. if (user.match("([^a-zA-Z0-9_]+)") != null || user.length < 3 || user.length > 15) {  
  17. alert("您输入的用户名应由字母数字下划线组成,长度在3~15位之间!");  
  18. return false;  
  19. }  
  20. else   
  21. if ((pass.length > 20 || pass.length < 6) || (pass == user)) {  
  22. alert("您的密码长度过短或者密码与姓名相同,请重新输入!");  
  23. return false;  
  24. }  
  25. else   
  26. if (pass != rpass) {  
  27. alert("您两次输入的密码不一致!");  
  28. return false;  
  29. }  
  30. else   
  31. //身份证号用于匹配两种模式,一种是15位的,一种是18位的  
  32. //这个正则表达式分三部分:第一位必须为1,最后一位可以是x、X、0-9中的任意一位  
  33. //中间一块是指匹配13或者16位数字  
  34. if (cardnum.match("1\\d{16}[0-9xX]+|1\\d{13}[0-9xX]+") == null) {  
  35. alert("您的身份证号码不正确,请重新输入!");  
  36. return false;  
  37. }  
  38. else   
  39. //正则表达式匹配a-zA-Z0-9_中的一位或者多位,而且必须要有@.这是一个email必须的  
  40. if (email.match("[a-zA-Z0-9_]*@.") == null) {  
  41. alert("您输入的E-Mail不正确,请重新输入!");  
  42. return false;  
  43. }  
  44. else {  
  45. alert("登陆成功!");  
  46. }  
  47. }  
  48. </script> 
  49. </head> 
  50. <body> 
  51. <form action="ff.html" method="get" onsubmit="return check();"> 
  52. 用户名:<input id="username" type="text" name="username"/><p/>密 码: <input id="pass" type="password" name="password"/><p/>重新输入密码:<input id="rpass" type="password"/><p/>身份证号码:<input id="cardnum" type="text"/><p/>E-Mail:<input id="email" type="text"/> 
  53. <br/> 
  54. <br/> 
  55. <input type="submit" value="提交" /><input type="reset" value="重置"/> 
  56. </form> 
  57. </body> 
  58. </html> 

 

本文出自 “乔磊的博客 学习 进步” 博客,请务必保留此出处http://sucre.blog.51cto.com/1084905/380692

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部