Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var validateRequiredFields = (function () {
- var errorcount = 0;
- var formFieldData = []; // array will hold information about all required form fields
- var self = {
- prepareData: function (container) {
- var $selector = $(container),
- $requiredFields = $selector.find('.js-required');
- return self.validateFields($requiredFields);
- },
- validateFields: function (fields) {
- errorcount = 0; // reset error counter before re-validating fields
- $.each(fields, function () {
- var $this = $(this),
- fieldName = $(this).attr('name'),
- isFound = self.findInArr(fieldName, formFieldData);
- 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
- var fieldObj = {};
- fieldObj.name = $this.attr('name');
- fieldObj.val = $this.val();
- formFieldData.push(fieldObj);
- $this.on('change', function (e) {
- e.preventDefault();
- self.addOrRemoveInvalidClass($this);
- });
- }
- self.addOrRemoveInvalidClass($this);
- });
- return (errorcount > 0) ? false : true;
- },
- addOrRemoveInvalidClass: function (field) {
- var $currentField = field;
- if (!$currentField.val()) {
- errorcount.length ? errorcount-- : errorcount++;
- if ($currentField.hasClass('select2-hidden-accessible')) { // to get correct input container from the Select2
- $currentField = $currentField.parent().find('span.select2-selection');
- }
- $currentField.addClass('field-invalid');
- }
- else {
- if ($currentField.hasClass('select2-hidden-accessible')) { // to get correct input container from the Select2
- $currentField = $currentField.parent().find('span.select2-selection');
- }
- $currentField.removeClass('field-invalid');
- }
- },
- findInArr: function (value, array) {
- var isFound = -1;
- if (!array.length) {
- return isFound;
- }
- for (var i = 0; i < array.length; i++) {
- if (array[i].name === value) {
- isFound = i;
- }
- if (i === array.length -1) {
- return isFound;
- }
- }
- }
- };
- return {
- validate: self.prepareData
- };
- })();
Add Comment
Please, Sign In to add comment