I am trying to validate two dates (one can’t be smaller than the other) with javascript and dynamic action. Currently it works but only when I pick a date and save it (it lets me pick a smaller date when it shouldn’t) and when I edit the entry that’s when the error message pops up. Can’t seem to figure out how to make the error pop up immediately after picking an incorrect date.
This is javascript code and I am calling the function in dynamic action set to change-columns-departure
function validateDates() {
console.log("Validation function called");
var regionStaticId = "my_ig";
var grid;
try {
grid = apex.region(regionStaticId).widget().interactiveGrid("getViews", "grid");
} catch (e) {
console.error("Interactive grid not found.", e);
return;
}
var model = grid.model;
var arrivalIdx = model.getFieldKey("ARRIVAL");
var departureIdx = model.getFieldKey("DEPARTURE");
// Clear any previous error messages
apex.message.clearErrors();
// Get the current editable record
var editableView = grid.view$.grid("getSelectedRecords");
if (editableView.length > 0) {
var record = editableView[0];
var arrival = record[arrivalIdx];
var departure = record[departureIdx];
console.log("Checking record: ", record);
console.log("Arrival: ", arrival, "Departure: ", departure);
// Check if the dates are valid and if "Departure" date is smaller than "Arrival" date
if (arrival && departure) {
var arrivalDate = new Date(arrival);
var departureDate = new Date(departure);
console.log("Arrival Date: ", arrivalDate, "Departure Date: ", departureDate);
if (departureDate < arrivalDate) {
console.log("Invalid date detected");
// Show error message immediately
apex.message.showErrors([{
type: "error",
location: "page",
message: "Pick a different date.",
pageItem: null
}]);
// Re-focus the invalid cell to prompt correction
grid.view$.grid("gotoCell", {
row: model.getRecordId(record),
field: departureIdx
});
// Clear the invalid date
model.setValue(record, departureIdx, null);
}
}
} else {
console.error("No editable record selected.");
}
}
// Bind the validation function to the change event of the Departure column
$(document).on("change", "input[name=f06]", function() {
validateDates();
});
validateDates();