Validate scheduler drag and dropScheduler
Combine validateDrop and validateResize to block double bookings, keep jobs inside working hours and only assign work to qualified technicians.
A dispatcher drags jobs between technicians all day. Three rules keep the plan valid: a technician cannot be in two places at once, jobs stay inside working hours, and a job only goes to someone qualified for it. This recipe enforces all three with validateDrop and validateResize, and tells the dispatcher which rule blocked a move.
Loading demo…
View source
Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.
demos/recipe-scheduler-drag-validation.ts
import { createScheduler, type DropContext, type ResizeContext } from '@birchui/scheduler';
import { docsTheme, layout, onDocsThemeChange } from './_shared';
import { WEEK_START, serviceJobs, technicians, type ServiceJob, type Technician } from './_scheduler-data';
export const meta = { title: 'Drag validation: overlaps, working hours and trades', height: 480 };
const WORK_START_HOUR = 8;
const WORK_END_HOUR = 18;
const ELECTRICAL_JOBS = new Set(['tech-sam', 'tech-nora', 'tech-ben']);
interface TradeJob extends ServiceJob {
trade: string;
}
function withinWorkingHours(start: Date, end: Date): boolean {
const last = new Date(end.getTime() - 1);
const startHour = start.getHours() + start.getMinutes() / 60;
const endHour = end.getHours() + end.getMinutes() / 60 || 24;
return start.toDateString() === last.toDateString() && startHour >= WORK_START_HOUR && endHour <= WORK_END_HOUR;
}
export default function mount(el: HTMLElement): () => void {
const { toolbar, body, status } = layout(el);
toolbar.append(
'Try to drop a job onto another job, outside 08:00 to 18:00, or onto a technician from the other team. Rejected positions turn red.',
);
const end = new Date(WEEK_START);
end.setDate(end.getDate() + 5);
const jobs: TradeJob[] = serviceJobs().map((job) => ({
...job,
trade: ELECTRICAL_JOBS.has(job.resourceId) ? 'elec' : 'hvac',
}));
let lastReason = '';
const overlaps = (id: string, start: Date, finish: Date, resourceId: string) =>
scheduler.getEventsInRange(start, finish, resourceId).some((other) => other.id !== id);
function reasonForDrop({ event, start, end: finish, resourceId, resource }: DropContext<TradeJob, Technician>) {
if (!resource?.parentId) return 'Jobs can only be assigned to a technician, not a team.';
if (resource.parentId !== event.trade) return `${resource.name} is not qualified for ${event.title.toLowerCase()}.`;
if (!withinWorkingHours(start, finish)) return 'Jobs must stay within 08:00 to 18:00 on one day.';
if (overlaps(event.id, start, finish, resourceId)) return `${resource.name} already has a job at that time.`;
return '';
}
function reasonForResize({ event, start, end: finish }: ResizeContext<TradeJob, Technician>) {
if (!withinWorkingHours(start, finish)) return 'Jobs must stay within 08:00 to 18:00 on one day.';
if (overlaps(event.id, start, finish, event.resourceId)) return 'The new length overlaps another job.';
return '';
}
const scheduler = createScheduler<TradeJob, Technician>(body, {
resources: technicians,
events: jobs,
start: WEEK_START,
end,
viewPreset: 'hourAndDay',
snap: 15,
createOnDrag: false,
workingTime: { days: [1, 2, 3, 4, 5], startHour: WORK_START_HOUR, endHour: WORK_END_HOUR },
validateDrop: (context) => {
lastReason = reasonForDrop(context);
return lastReason === '';
},
validateResize: (context) => {
lastReason = reasonForResize(context);
return lastReason === '';
},
theme: docsTheme(),
height: '100%',
ariaLabel: 'Field service schedule with drag validation',
});
const onPointerUp = () => {
if (lastReason) status.textContent = `Rejected: ${lastReason}`;
lastReason = '';
};
body.addEventListener('pointerup', onPointerUp);
const offs = [
scheduler.on('eventDrop', ({ event, resourceId }) => {
lastReason = '';
status.textContent = `${event.title} accepted for ${scheduler.getResourceById(resourceId)?.name ?? resourceId}.`;
}),
scheduler.on('eventResize', ({ event }) => {
lastReason = '';
status.textContent = `${event.title} resized.`;
}),
];
status.textContent = 'Validation results appear here.';
const stopTheme = onDocsThemeChange((theme) => scheduler.update({ theme }));
return () => {
body.removeEventListener('pointerup', onPointerUp);
for (const off of offs) off();
stopTheme();
scheduler.destroy();
};
}Steps#
- Add the fields your rules need to your event and resource types, such as a job's
tradeand a technician's team. - Write each rule as a small function that returns a reason, or an empty string when the change is allowed.
- Call the rules from
validateDropandvalidateResize, and returnfalsewhen any of them gives a reason. - Show the reason after the pointer is released. Validators run on every snapped position during a drag, so they must not show messages themselves.
The rules#
dispatch-rules.ts
import type { SchedulerApi, SchedulerEvent, SchedulerResource } from '@birchui/scheduler';
export interface Technician extends SchedulerResource {
trades: string[];
}
export interface WorkOrder extends SchedulerEvent {
trade: 'hvac' | 'electrical' | 'plumbing';
customer: string;
}
const WORK_START_HOUR = 8;
const WORK_END_HOUR = 18;
export function outsideWorkingHours(start: Date, end: Date): string {
const last = new Date(end.getTime() - 1);
const startHour = start.getHours() + start.getMinutes() / 60;
const endHour = end.getHours() + end.getMinutes() / 60 || 24;
const sameDay = start.toDateString() === last.toDateString();
return sameDay && startHour >= WORK_START_HOUR && endHour <= WORK_END_HOUR
? ''
: 'Work orders must stay within 08:00 to 18:00 on one day.';
}
export function notQualified(job: WorkOrder, technician: Technician | undefined): string {
if (!technician) return 'Work orders can only be assigned to a technician.';
return technician.trades.includes(job.trade) ? '' : `${technician.name} is not qualified for ${job.trade} work.`;
}
export function doubleBooked(
scheduler: SchedulerApi<WorkOrder, Technician>,
jobId: string,
start: Date,
end: Date,
technicianId: string,
): string {
const clash = scheduler.getEventsInRange(start, end, technicianId).find((other) => other.id !== jobId);
return clash ? `Clashes with ${clash.title} for ${clash.customer}.` : '';
}Apply them#
dispatch-board.ts
import { createScheduler } from '@birchui/scheduler';
import { doubleBooked, notQualified, outsideWorkingHours, type Technician, type WorkOrder } from './dispatch-rules';
let rejection = '';
const scheduler = createScheduler<WorkOrder, Technician>(document.querySelector<HTMLElement>('#dispatch')!, {
resources: technicians,
events: workOrders,
start: '2026-12-07',
end: '2026-12-12',
viewPreset: 'hourAndDay',
snap: 15,
workingTime: { days: [1, 2, 3, 4, 5], startHour: 8, endHour: 18 },
validateDrop: ({ event, start, end, resourceId, resource }) => {
rejection =
notQualified(event, resource) ||
outsideWorkingHours(start, end) ||
doubleBooked(scheduler, event.id, start, end, resourceId);
return rejection === '';
},
validateResize: ({ event, start, end }) => {
rejection = outsideWorkingHours(start, end) || doubleBooked(scheduler, event.id, start, end, event.resourceId);
return rejection === '';
},
});
scheduler.element.addEventListener('pointerup', () => {
if (rejection) showToast(rejection);
rejection = '';
});The validators refer to scheduler, which is safe: they run only during user interaction, after createScheduler has returned.
How it works#
- While the user drags, the validator runs on every snapped position. A rejected position turns the drag preview red, and releasing there leaves the event where it was. No
eventDroporeventResizeis emitted for a rejected change. - The
||chain stops at the first rule that fails, so the cheapest checks go first and the range query runs last. rejectionholds the reason from the last position checked. When the pointer is released on a valid position, the last check passed and the string is empty, so no message is shown.- Keyboard moves (Alt + arrow keys) run the same validators once per step.
Pitfalls#
- Validators must be synchronous. For checks only the server can make, accept the move and roll back in the
eventDroplistener. See Server-side checks and Save scheduler changes to a server. - Ignore the event itself.
getEventsInRangereturns the job being dragged at its old position too. Always filter it out by id. - Time zones.
getHours()reads the browser's zone. If the scheduler has atimeZoneoption, read the hour in that zone, as in Keep jobs inside working hours. - New events.
validateDropdoes not run for drag-to-create. Run the same rules in youreventCreatelistener before callingaddEvent. - Throwing validators are logged with
console.errorand reject the change.
Related#
- Validation in the interactions guide.
- Working time for shading non-working hours.
- Recurring jobs, where validators also apply to occurrences.