Posted By

nerdfiles on 12/14/09


Tagged

jquery validation


Versions (?)

Poor Man's jQuery Validation (or jQuery Proof)


 / Published in: JavaScript
 

Inspired by the reputable jQuery Validation plugin. I'll turn this into a proper plugin later... after I clean it up some.

Rule invocation by @class, so: @class="required", @class="e-mail", @class="digit", @class="zip", @class="min-length-10", @class="max-length-100"

Caveat: Error handling assumes that the input, select, etc field are wrapped in a division which distinguishes them from their respective label (and its wrapping division). My mark-up of form fields is a bit cumbersome, but I believe it gives me flexibility and structural consistency (it's irritating to only wrap the input[type='file'] in many divisions while the rest of the form fields don't receive the same service).

Invoke like so: var options = { livetype: true }; $proof.validator( $('#sms-form'), options );

  1. Array.prototype.unique = function () {
  2. var r = new Array();
  3. o:for(var i = 0, n = this.length; i < n; i++)
  4. {
  5. for(var x = 0, y = r.length; x < y; x++)
  6. {
  7. if(r[x]==this[i])
  8. {
  9. continue o;
  10. }
  11. }
  12. r[r.length] = this[i];
  13. }
  14. return r;
  15. }
  16.  
  17. $proof = {
  18.  
  19. errorStoreTest: [],
  20.  
  21. options: {
  22. livetype: false
  23. },
  24.  
  25. pattern: {
  26. "required": {
  27. filter: /^\S+$/,
  28. msg: "Please fill in this field."
  29. },
  30. "e-mail": {
  31. filter: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/,
  32. msg: "Please provide a valid e-mail address."
  33. },
  34. "digits": {
  35. filter: /^\d+$/,
  36. msg: "Please enter digits only."
  37. },
  38. "zip": {
  39. filter: /(^\d{5}$)|(^\d{5}-\d{4}$)/,
  40. msg: "Please provide a valid zip or postal code."
  41. },
  42. "min-length": {
  43. filter: /^.{0,}$/,
  44. msg: "Min length error."
  45. },
  46. "max-length": {
  47. filter: /^.{0,65535}$/,
  48. msg: "Max length error."
  49. }
  50. },
  51.  
  52. validator: function(form, options) {
  53. var validate = this;
  54. var defaults = this.options;
  55.  
  56. if(options) {
  57. //use custom options
  58. } else {
  59. //use defaults
  60. }
  61.  
  62. form.submit(function(e) {
  63. var elems = form.find(':input[class*=required], :input[class*=e-mail], :input[class*=number], :input[class*=zip], :input[class*=min-length], :input[class*=max-length]');
  64. //var elems = form.find(':input[class*=required], :input[class*=number], :input[class*=zip], :input[class*=min-length], :input[class*=max-length]');
  65.  
  66. //reset error business
  67. var errorStore = {};
  68.  
  69. validate.errorStoreTest = [];
  70.  
  71. $('#error-container').remove();
  72. var errorOutputHead = "<div id=\"error-container\"><div class=\"content\"><p></p><ul>";
  73. var errorOutput = "";
  74. var errorOutputFoot = "</ul></div></div>";
  75. form.find('input.error, textarea.error, select.error').removeClass('error');
  76.  
  77. //validate options into array to isolate and test against only them
  78. var a = [];
  79. for (name in validate.pattern) {
  80. a.push(name);
  81. }
  82.  
  83. //check for errors
  84. for (var i = 0; i < elems.length; i += 1) {
  85. var elem = $(elems[i]);
  86. var elemClass = elem.attr('class');
  87. var elemClassSplit = elemClass.split(" ");
  88.  
  89.  
  90. for (var j = 0; j < elemClassSplit.length; j += 1) {
  91. //validate options into array to isolate and test against only them
  92. var newElemPatternType = elemClassSplit[j];
  93.  
  94. //for min/max (it's ugly, I know -- guh)
  95. var result = /min-length-\d|max-length-\d/.exec(elemClassSplit[j]);
  96. if(result) {
  97. if (result.toString().indexOf('min') != -1) {
  98. var min = elemClassSplit[j].toString().split("-")[2];
  99. var newElemPatternType = newElemPatternType.replace("-"+min, ""); //reshapes to ping pattern name
  100. var newFilter = validate.pattern[newElemPatternType].filter.toString();
  101. newFilter = newFilter.replace("0", min);
  102. } else {
  103. var max = elemClassSplit[j].toString().split("-")[2];
  104. var newElemPatternType = newElemPatternType.replace("-"+max, ""); //reshapes to ping pattern name
  105. var newFilter = validate.pattern[newElemPatternType].filter.toString();
  106. newFilter = newFilter.replace("65535", max);
  107. }
  108. } else {
  109. if ( $.inArray(newElemPatternType, a) != -1 ) {
  110. var newFilter = validate.pattern[newElemPatternType].filter.toString();
  111. }
  112. }
  113.  
  114. if ( $.inArray(newElemPatternType, a) != -1 ) {
  115.  
  116. //parse out the modifier and slashes, since we cannot convert
  117. //valid regex [strings] back into regex objects
  118. newFilter = newFilter.replace("\\", "\\").replace("/", "").replace("/", "").replace("i", "").toString();
  119. var reg = new RegExp(newFilter);
  120.  
  121. if ( !reg.test(elem.val()) ) {
  122. //errors! - for inline presentation
  123. elem.parent().addClass('error');
  124. elem.addClass('error');
  125.  
  126. //errors! - for error block
  127. //errorStore.names.push("#"+elem.attr('id'));
  128. //errorStore.types.push(validate.pattern[newElemPatternType]);
  129. //errorStore.messages.push(validate.pattern[newElemPatternType].msg);
  130.  
  131. var error_name = elem.attr('id').toString();
  132.  
  133.  
  134. validate.errorStoreTest.push({
  135. error: {
  136. error_id: "#"+error_name,
  137. error_type: {
  138. error_type_name: newElemPatternType,
  139. error_filter: newFilter,
  140. error_msg: validate.pattern[newElemPatternType].msg
  141. }
  142. }
  143. });
  144.  
  145. errorOutput += "<li><label for=\""+elem.attr('id')+"\"><span class=\"field-name\">"+elem.parent().prev().find('label').text()+"</span> <span class=\"field-error-msg\">"+validate.pattern[newElemPatternType].msg+"</span></label></li>";
  146. }
  147. }
  148. }
  149. }
  150.  
  151. if(options.livetype) {
  152. var errStr = validate.errorStoreTest;
  153. for (var k = 0; k < errStr.length; k += 1) {
  154. var livereg = new RegExp(errStr[k].error.error_type.error_filter.toString());
  155. $(errStr[k].error.error_id).queue(function() {
  156. $(this).change(function() {
  157. var valStr = $(this).val();
  158. if ( !livereg.test(valStr) ) {
  159. $(this).addClass('error');
  160. } else
  161. } else {
  162. delete errStr[k];
  163. }
  164.  
  165.  
  166. //alert( errStr.length );
  167. });
  168. });
  169. }
  170. }
  171.  
  172. if(validate.errorStoreTest.length) {
  173. //display error block
  174. form.before(errorOutputHead+errorOutput+errorOutputFoot);
  175. e.preventDefault();
  176. } else {
  177. //remove it if the array is empty
  178. $('#error-container').remove();
  179. }
  180.  
  181. //clean up?
  182.  
  183. });
  184. }
  185. };

Report this snippet  

You need to login to post a comment.