Anyone find a way to get validations which are dependent on other fields to work? Trying to get a validation to ensure that an end date is after a start date. Ive tried playing around with equations and conditional rules but they seem to run after form submission not before, and the current validation system can only check against a hardcoded value, not another data field.
This can only be done using custom JavaScript. Here’s a snippet for you to try:
(function () {
// View IDs
const FORM_VIEW = 'view_1'; // your form's view key
// Field IDs
const START_DATE_FIELD = 'field_1'; // Start Date
const END_DATE_FIELD = 'field_2'; // End Date
// Configuration
const ERROR_ID = 'date-range-error';
const ERROR_TEXT = 'End Date must be after Start Date.';
$(document).on('knack-view-render.' + FORM_VIEW, function (event, view) {
// Selectors (built from view.key, only available at render time)
const START = '#' + view.key + '-' + START_DATE_FIELD;
const END = '#' + view.key + '-' + END_DATE_FIELD;
const SUBMIT = '#' + view.key + ' button[type="submit"]';
// Knack date fields render as MM/DD/YYYY text - parse explicitly,
// don't rely on new Date(str) (it's locale/parser dependent)
function parseDate(str) {
if (!str) return null;
const p = str.split('/');
if (p.length !== 3) return null;
return new Date(+p[2], +p[0] - 1, +p[1]); // year, month-1, day
}
function validate() {
const start = parseDate($(START).val());
const end = parseDate($(END).val());
if (!start || !end) return; // wait until both are filled
if (end < start) {
if (!$('#' + ERROR_ID).length) {
$(END).closest('.kn-input').append(
'<div id="' + ERROR_ID + '" style="color:red;margin-top:5px;">' + ERROR_TEXT + '</div>'
);
}
$(SUBMIT).prop('disabled', true).css('opacity', 0.5);
} else {
$('#' + ERROR_ID).remove();
$(SUBMIT).prop('disabled', false).css('opacity', 1);
}
}
$(START + ', ' + END).on('input change blur', validate);
});
})();