# Validate scheduler drag and drop

> 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.

**Live demo: Drag validation: overlaps, working hours and trades** (runs on the HTML version of this page). Source of `demos/recipe-scheduler-drag-validation.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```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

1. Add the fields your rules need to your event and resource types, such as a job's `trade` and a technician's team.
2. Write each rule as a small function that returns a reason, or an empty string when the change is allowed.
3. Call the rules from `validateDrop` and `validateResize`, and return `false` when any of them gives a reason.
4. 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

```ts title="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

```ts title="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 `eventDrop` or `eventResize` is 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.
- `rejection` holds 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 (<kbd>Alt</kbd> + 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 `eventDrop` listener. See [Server-side checks](https://docs.birchui.com/scheduler/interactions.md#server-side-checks) and [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md).
- **Ignore the event itself.** `getEventsInRange` returns 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 a `timeZone` option, read the hour in that zone, as in [Keep jobs inside working hours](https://docs.birchui.com/scheduler/interactions.md#keep-jobs-inside-working-hours).
- **New events.** `validateDrop` does not run for drag-to-create. Run the same rules in your `eventCreate` listener before calling `addEvent`.
- **Throwing validators** are logged with `console.error` and reject the change.

## Related

- [Validation](https://docs.birchui.com/scheduler/interactions.md#validation) in the interactions guide.
- [Working time](https://docs.birchui.com/scheduler/working-time.md) for shading non-working hours.
- [Recurring jobs](https://docs.birchui.com/recipes/scheduler-recurring-jobs.md), where validators also apply to occurrences.

**`DropContext`** (interface from `@birchui/scheduler`, full reference: https://docs.birchui.com/api/scheduler.md)

```ts
interface DropContext<TEvent extends SchedulerEvent, TResource extends SchedulerResource>
```

| Property | Type | Description |
| --- | --- | --- |
| `event` | `TEvent` |  |
| `start` | `Date` |  |
| `end` | `Date` |  |
| `resourceId` | `string` |  |
| `resource` | `TResource \| undefined` |  |
| `previous` | `{ start: Date; end: Date; resourceId: string }` |  |
