Posted By

alvincrespo on 02/19/10


Tagged

form javascript oop prototype validation validator


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

rzhome
nerdfiles
aaearhart


Javascript OOP Form Validator


 / Published in: JavaScript
 

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. }

Report this snippet  

You need to login to post a comment.