Skip to content

Instantly share code, notes, and snippets.

@ChuckBryan
Created May 23, 2019 12:11
Show Gist options
  • Save ChuckBryan/e903c75715a15ead747bf10823066bae to your computer and use it in GitHub Desktop.
Save ChuckBryan/e903c75715a15ead747bf10823066bae to your computer and use it in GitHub Desktop.
'use strict';
// IIFE - Immediately Invoked Function Expression
(function(ajaxvalidationsetip) {
// The global jQuery object is passed as a parameter
ajaxvalidationsetip(window.jQuery, window, document);
}(function($, window, document) {
//console.log($.ajax);
// When the Ajax returns a 200 Response, it will either redirect or reload the screen
var redirect = function (data) {
if (data.hasAlert) {
window.sessionStorage.setItem("_Alert", JSON.stringify({
message: data.message,
alertClass: data.alertClass
}));
}
if (data.redirect) {
window.location = data.redirect;
} else {
window.scrollTo(0, 0);
window.location.reload();
}
};
// Add Errors to the Validation Summary
var showSummary = function (response) {
$('#validationSummary').empty().removeClass('hidden');
var verboseErrors = _.flatten(_.map(response, 'Errors')),
errors = [];
var nonNullErrors = _.reject(verboseErrors, function (error) {
return error.ErrorMessage.indexOf('must not be empty') > -1;
});
_.each(nonNullErrors, function (error) {
errors.push(error.ErrorMessage);
});
if (nonNullErrors.length !== verboseErrors.length) {
errors.push('The highlighted fields are required to submit this form.');
}
var $ul = $('#validationSummary').append('<ul></ul>');
_.each(errors, function (error) {
var $li = $('<li></li>').text(error);
$li.appendTo($ul);
});
};
// Iterate over each of the errors in the response, find the form-group and add the has-error class.
var highlightFields = function (response) {
$('.form-group').removeClass('has-error');
$.each(response, function (propName, val) {
var nameSelector = '[name = "' + propName.replace(/(:|\.|\[|\])/g, "\\$1") + '"]',
idSelector = '#' + propName.replace(/(:|\.|\[|\])/g, "\\$1");
var $el = $(nameSelector) || $(idSelector);
var errorSpan = $('span[data-valmsg-for="' + val.Key + '"]');
errorSpan.text("");
if (val.Errors.length > 0) {
$el.closest('.form-group').addClass('has-error');
var errorMessage = val.Errors[0].ErrorMessage;
errorSpan.addClass('text-danger');
// Update Html instead of text in case any html is returned in the message
errorSpan.html(errorMessage);
}
});
};
// If the Ajax returns an error (e.g. 400), then run this coe to hightlight
var highlightErrors = function(xhr) {
try {
var data = JSON.parse(xhr.responseText);
highlightFields(data);
showSummary(data);
window.scrollTo(0, 0);
} catch (e) {
// (Hopefully) caught by the generic error handler in `config.js`.
}
};
// $('form[method=post]').not('.no-ajax').on('submit',
$('body').on('submit', 'form[method=post]:not(.no-ajax)',
function(e) {
var submitBtn = $(this).find('[type="submit"]');
submitBtn.prop('disabled', true);
$(window).unbind();
var $this = $(this),
formData = $this.serializeArray();
//formData.removeMasks();
$.each(formData,
function(index, item) {
var input = $('#' + item.name + '[data-mask]:not([data-mask-keep])');
if (input.length !== 0) {
item.value = input.cleanVal();
}
});
$this.find('div').removeClass('has-error');
$.ajax({
url: $this.attr('action'),
type: 'post',
data: $.param(formData),
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: 'json',
statusCode: {
200: redirect
},
complete: function() {
submitBtn.prop('disabled', false);
}
}).fail(function(data) {
highlightErrors(data);
});
return false;
});
}
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment