Guest User

Untitled

a guest
Jul 23rd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. var validateRequiredFields = (function () {
  2.  
  3. var errorcount = 0;
  4. var formFieldData = []; // array will hold information about all required form fields
  5.  
  6. var self = {
  7.  
  8. prepareData: function (container) {
  9.  
  10. var $selector = $(container),
  11. $requiredFields = $selector.find('.js-required');
  12.  
  13. return self.validateFields($requiredFields);
  14.  
  15. },
  16. validateFields: function (fields) {
  17.  
  18. errorcount = 0; // reset error counter before re-validating fields
  19.  
  20. $.each(fields, function () {
  21. var $this = $(this),
  22. fieldName = $(this).attr('name'),
  23. isFound = self.findInArr(fieldName, formFieldData);
  24.  
  25. if (isFound === -1) { // if this field is not found on form field array, push field information into array and add a listener which will listen for change event
  26.  
  27. var fieldObj = {};
  28. fieldObj.name = $this.attr('name');
  29. fieldObj.val = $this.val();
  30.  
  31. formFieldData.push(fieldObj);
  32.  
  33. $this.on('change', function (e) {
  34. e.preventDefault();
  35. self.addOrRemoveInvalidClass($this);
  36. });
  37. }
  38.  
  39. self.addOrRemoveInvalidClass($this);
  40. });
  41.  
  42. return (errorcount > 0) ? false : true;
  43.  
  44. },
  45. addOrRemoveInvalidClass: function (field) {
  46.  
  47. var $currentField = field;
  48.  
  49. if (!$currentField.val()) {
  50.  
  51. errorcount.length ? errorcount-- : errorcount++;
  52.  
  53. if ($currentField.hasClass('select2-hidden-accessible')) { // to get correct input container from the Select2
  54. $currentField = $currentField.parent().find('span.select2-selection');
  55. }
  56.  
  57. $currentField.addClass('field-invalid');
  58. }
  59. else {
  60.  
  61. if ($currentField.hasClass('select2-hidden-accessible')) { // to get correct input container from the Select2
  62. $currentField = $currentField.parent().find('span.select2-selection');
  63. }
  64.  
  65. $currentField.removeClass('field-invalid');
  66. }
  67. },
  68. findInArr: function (value, array) {
  69.  
  70. var isFound = -1;
  71.  
  72. if (!array.length) {
  73. return isFound;
  74. }
  75.  
  76. for (var i = 0; i < array.length; i++) {
  77. if (array[i].name === value) {
  78. isFound = i;
  79. }
  80.  
  81. if (i === array.length -1) {
  82. return isFound;
  83. }
  84. }
  85. }
  86. };
  87.  
  88. return {
  89. validate: self.prepareData
  90. };
  91.  
  92. })();
Add Comment
Please, Sign In to add comment