Wednesday, October 19, 2011

Javascript - Parse Date, Get Difference

These functions will compute the difference of two given dates in Javascript.
For example:
var deadline = parseDate("2012-02-07");
var startdate = parseDate("2011-12-25");

var daysToFinish = daysDifference(deadline,startdate);
var weeksToFinish = weeksDifference(deadline,startdate);
var yearsToFinish = yearsDifference(deadline,startdate);

var daysToGo = daysFromNow(deadline);
var weeksToGo = weeksFromNow(deadline);
var yearsToGo = yearsFromNow(deadline);


  • parseDate(dateString) 
    • returns a date object based from string.

    • function parseDate(dateString){
      var dateParts = dateString.split('-');
      var yearIndex = 0;
      var monthIndex = 1;
      var dayIndex = 2;
      return new Date(dateParts[yearIndex], dateParts[monthIndex]-1, dateParts[dayIndex]);
      //or simply
      //return new Date(str);
      }
  • daysDifference(sourceDate, compareDate) 
    • returns the number of days difference with Date objects as parameters.

    • function daysDifference(sourceDate, compareDate){
      var oneDay = 1000*60*60*24;
      var daysDifference = (sourceDate-compareDate) / oneDay;
      return daysDifference.toFixed(2);
      }
  • weeksDifference(sourceDate, compareDate) 
    • returns the number of weeks difference with Date objects as parameters.

    • function weeksDifference(sourceDate, compareDate){
      var oneWeek = 1000*60*60*24*7;
      var weeksDifference = (sourceDate-compareDate) / oneWeek;
      return weeksDifference.toFixed(2);
      }
  • yearsDifference(sourceDate, compareDate) 
    • returns the number of years difference with Date objects as parameters.

    • function yearsDifference(sourceDate, compareDate){
      var oneYear = 1000*60*60*24*365.26; //approximate
      var yearsDifference = (sourceDate-compareDate) / oneYear;
      return yearsDifference.toFixed(2);
      }
  • daysFromNow(sourceDate) 
    • returns the number of days difference between a given date and the current date.

    • function daysFromNow(sourceDate){
      var currentDate = new Date();
      return daysDifference(sourceDate,currentDate);
      }
  • weeksFromNow(sourceDate) 
    • returns the number of weeks difference between a given date and the current date.

    • function weeksFromNow(sourceDate){
      var currentDate = new Date();
      return weeksDifference(sourceDate,currentDate);
      }
  • yearsFromNow(sourceDate) 
    • returns the number of years difference between a given date and the current date.

    • function yearsFromNow(sourceDate){
      var currentDate = new Date();
      return yearsDifference(sourceDate,currentDate);
      }


Sunday, October 9, 2011

JQuery - validate plugin for dependency validation (i.e. fields required if 1 has value))

This code will give you an option to make some fields required if a source field has some value. If the source field has no value, then other fields are not required. You can also have the option to equire all dependencies or at least one of them have a value.
function validateDependency(sourceClassname, dependentClassname, message, requireAll) {
jQuery.validator.addMethod(sourceClassname, function (val, el) {
var textboxes = $(':input:text[class^="' + sourceClassname + '"]:filled').length;
var checkboxes = $(':input:checkbox[class^="' + sourceClassname + '"]:checked').length;
var radios = $(':input:radio[class^="' + sourceClassname + '"]:checked').length;
if (textboxes || checkboxes || radios) {
textboxes = $(':input:text[class^="' + dependentClassname + '"]:filled').length;
checkboxes = $(':input:checkbox[class^="' + dependentClassname + '"]:checked').length;
radios = $(':input:radio[class^="' + dependentClassname + '"]:checked').length;

if (requireAll) {
textboxes = ($(':input:text[class^="' + dependentClassname + '"]').length == textboxes);
checkboxes = ($(':input:checkbox[class^="' + dependentClassname + '"]').length == checkboxes);
radios = ($(':input:radio[class^="' + dependentClassname + '"]').length == radios);

return (textboxes && checkboxes && radios);
}
return (textboxes || checkboxes || radios);
}
else
return true;
}, (message != null ? message : 'Please fill out at least one of these fields'));
}

JQuery - validate plugin for group validation (i.e. at least 1 required field)


Here's how to validate group using JQuery's Validate Plugin. You must add your own method for the group validation.

function validateGroup(classname, message) {
jQuery.validator.addMethod(classname, function (val, el) {
var textboxes = $(':input:text[class^="' + classname + '"]:filled').length;
var checkboxes = $(':input:checkbox[class^="' + classname + '"]:checked').length;
var radios = $(':input:radio[class^="' + classname + '"]:checked').length;

return textboxes || checkboxes || radios;
}, (message != null ? message : 'Please fill out at least one of these fields'));
}


With the group validation, JQuery will display several error messages for a group of textboxes. It is so annoying becaue I only wanted to display 1 error message for the whole group rather than on each field. Since I haven't found yet the solution on how to do that using the JQuery plugin, I override the "invalidHandler" function for the plugin. Here's what I did.

function validateForm(formname,errorContainer) {
jQuery.validator.messages.required = "You missed some required fields.";
var formObject;
if (formname)
formObject = $("#" + formname);
else
formObject = $('input[name="submitButton"]').closest("form");

formObject.validate({
errorClass: "invalid",
highlight: function (element, errorClass) {
$(element).addClass(errorClass);
$(element.form).find("label[for=" + element.id + "]")
.addClass(errorClass);
},
unhighlight: function (element, errorClass) {
$(element).removeClass(errorClass);
$(element.form).find("label[for=" + element.id + "]")
.removeClass(errorClass);
},
errorContainer: "#" + errorContainer,
errorLabelContainer: "#" + errorContainer + " ul",
wrapper: "li",
errorElement: "span",
invalidHandler: function (form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
message = "" + message + "

    "; var errorListing = new Array(); $.each(validator.errorList, function (index, value) { if ($.inArray(value.message, errorListing) < 0) {
    errorListing.push(value.message);
    message += "
  • " + value.message + "

  • "; } }); message += "
";
ScreenManager.Error(null,message);
} else {
//$("div.error").hide();
}
}

});
}

Here's a sample usage of the script:



If somebody knew a better approach to this, please let me know.