Javascript OOP表单验证程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javascript OOP表单验证程序相关的知识,希望对你有一定的参考价值。

Just thought id put up a version of my form validation class. It will be expanded in the future but I thought Id let everyone have a look.

# Update 0.1 #
* Create Error List Function
* Validate Email Address Function
* Validate Length of field
  1. /*
  2. Author: Alvin Crespo
  3. Date: 2/18/2010
  4.  
  5. Description: javascript Field Validation Class
  6. */
  7.  
  8.  
  9. function ValidateFields(pFormID){
  10. var aForm = document.getElementById(pFormID);
  11. this.errArray = new Array();//error tracker
  12. }
  13.  
  14. /*
  15.  * ValidateEmail
  16.  *
  17.  * @id - id element of the email addres
  18.  *
  19.  * Validates a given email address
  20.  *
  21.  * returns nothing
  22.  * */
  23. ValidateFields.prototype.ValidateEmail = function(id){
  24.  
  25. var emailVal = document.getElementById(id).value;
  26.  
  27. //check length of email
  28. if(this.ValidateLength(emailVal)){
  29. this.errArray.push("You must provide an email.");
  30. return;
  31. }
  32. else{
  33. //do nothing
  34. }
  35.  
  36. //check validity of the email using regex
  37. var regexpr = /^([0-9a-zA-Z]([-.w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+[a-zA-Z]{2,9})$/;
  38. var emailResult = regexpr.test(emailVal);
  39.  
  40. if(!emailResult){
  41. this.errArray.push("Your email is invalid.");
  42. return;
  43. }
  44. else{
  45. //do nothing
  46. }
  47. }
  48. /*
  49.  * ValidateLength()
  50.  *
  51.  * @aFieldEle - element of a field
  52.  *
  53.  * Validates the length of a given element
  54.  *
  55.  * returns true or false
  56.  * */
  57. ValidateFields.prototype.ValidateLength = function(aFieldEle){
  58. //check that the value is greater than 0
  59. if(aFieldEle.length <= 0){
  60. return true; //less than 0
  61. }
  62. else{
  63. return false; //greater than 0
  64. }
  65. }
  66.  
  67. /*
  68.  * CreateErrorList()
  69.  *
  70.  * @formstatid - id of a form
  71.  *
  72.  * Places the errors after the form
  73.  *
  74.  * returns nothing
  75.  */
  76. ValidateFields.prototype.CreateErrorList = function(formstatid){
  77. var statList = document.getElementById(formstatid).getElementsByTagName('ul')[0];
  78. for(var i = 1; i<=this.errArray.length; i++){
  79. var aLI = document.createElement('li');
  80. var aLIText = document.createTextNode(this.errArray[i-1]);
  81. aLI.appendChild(aLIText);
  82. statList.appendChild(aLI);
  83. }
  84. }

以上是关于Javascript OOP表单验证程序的主要内容,如果未能解决你的问题,请参考以下文章

使用oop php进行表单验证

原生JavaScript判断是否为邮箱危险字符验证长度验证网址验证小数整数浮点数等常用的验证

JavaScript Javascript OOP表格验证器

VSCode自定义代码片段——JS中的面向对象编程

VSCode自定义代码片段9——JS中的面向对象编程

尝试通过Javascript验证表单,但代码不起作用