본문으로 건너뛰기Skip to content
예제 첫화면Examples home

여러 칸의 관계를 줄 단위로 검증하기Validate relations between cells per row

칸 하나의 규칙으로는 시작과 종료처럼 두 칸의 관계를 검사하기 어려워요. 줄 검증은 줄을 확정할 때 줄 전체를 보고 문제가 있는 칸과 이유를 알려 줘요. 문제가 있으면 그 줄이 고칠 때까지 열려 있어요.A per-cell rule cannot compare two cells such as start and end. rowValidator looks at the whole row when it is committed and reports which cell is wrong and why; the row stays open until fixed.

활용Intermediate
직접 써 보기Live preview여러 칸의 관계를 줄 단위로 검증하기Validate relations between cells per row

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="editMorning">오전조 시작 편집</button>
  </div>
  <div id="grid" style="height: 245px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('editMorning').addEventListener('click', () => actions.editMorning(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const rows = [
  { id: 1, shift: '오전조', start: 6, end: 14 },
  { id: 2, shift: '오후조', start: 14, end: 22 },
  { id: 3, shift: '야간조', start: 22, end: 24 },
];
// 칸 하나의 규칙(validation)은 다른 칸과 비교하기 어려워요. rowValidator는 "줄 하나를 확정할 때" 줄 전체를 보고
// { 컬럼: 이유 } 모양으로 문제를 돌려줘요. 문제가 있으면 그 줄은 고칠 때까지 열려 있어요(editMode: 'row').
export const options = {
  editMode: 'row',
  rowValidator: (row) => {
    if (row.end <= row.start)
      return {
        end: L('종료 시간은 시작 시간보다 늦어야 해요.', 'The end time must be later than the start time.'),
      };
    if (row.end - row.start > 10)
      return {
        end: L(`하루 근무는 최대 10시간이에요. (지금 ${row.end - row.start}시간)`, `A day is at most 10 hours. (now ${row.end - row.start} hours)`),
      };
    return null;
  },
  columns: [
    { id: 'shift', title: '조', width: 110 },
    {
      id: 'start',
      title: '시작(시)',
      kind: 'number',
      width: 110,
      align: 'end',
      editable: true,
      validation: { min: 0, max: 23 },
    },
    {
      id: 'end',
      title: '종료(시)',
      kind: 'number',
      width: 110,
      align: 'end',
      editable: true,
      validation: { min: 0, max: 24 },
    },
  ],
  rows,
  rowKey: 'id',
};
export function setup(api, log) {
  log({
    ko: '종료 시간을 시작보다 이르게 고쳐 보세요. 줄을 확정할 때 검사돼요.',
    en: 'Edit the end time to be earlier than the start. It is checked when the row is confirmed.',
  });
  const offs = [
    // 틀린 이유는 줄 안에 바로 나오니, 기록에는 같은 말을 또 적지 않아요(기록이 길어지면 틀 높이를 넘어요).
    api.on('rowEditCommitted', (e) => log({ ko: `✓ ${e.rowKey}번 줄을 저장했어요`, en: `✓ Row ${e.rowKey} saved` })),
    api.on('rowEditCancelled', (e) => log({ ko: `↺ ${e.rowKey}번 줄 편집을 취소했어요`, en: `↺ Row ${e.rowKey} edit cancelled` })),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  editMorning: (api) => api.startEdit(1, 'start'),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="editMorning">Edit morning start</button>
  </div>
  <div id="grid" style="height: 245px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('editMorning').addEventListener('click', () => actions.editMorning(api));
example.js
const rows = [
  { id: 1, shift: 'Morning', start: 6, end: 14 },
  { id: 2, shift: 'Afternoon', start: 14, end: 22 },
  { id: 3, shift: 'Night', start: 22, end: 24 },
];
// A per-cell rule (validation) cannot compare against other cells. rowValidator looks at the whole row when it is committed
// and returns problems as { column: reason }. A row with a problem stays open until fixed (editMode: 'row').
export const options = {
  editMode: 'row',
  rowValidator: (row) => {
    if (row.end <= row.start)
      return { end: 'The end time must be later than the start time.' };
    if (row.end - row.start > 10)
      return { end: `A day is at most 10 hours. (now ${row.end - row.start} hours)` };
    return null;
  },
  columns: [
    { id: 'shift', title: 'Shift', width: 110 },
    {
      id: 'start',
      title: 'Start (h)',
      kind: 'number',
      width: 110,
      align: 'end',
      editable: true,
      validation: { min: 0, max: 23 },
    },
    {
      id: 'end',
      title: 'End (h)',
      kind: 'number',
      width: 110,
      align: 'end',
      editable: true,
      validation: { min: 0, max: 24 },
    },
  ],
  rows,
  rowKey: 'id',
};
export function setup(api, log) {
  log('Edit the end time to be earlier than the start. It is checked when the row is confirmed.');
  const offs = [
    // The reason shows right in the row, so the log does not repeat it (a long log would overflow the frame height).
    api.on('rowEditCommitted', (e) => log(`✓ Row ${e.rowKey} saved`)),
    api.on('rowEditCancelled', (e) => log(`↺ Row ${e.rowKey} edit cancelled`)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  editMorning: (api) => api.startEdit(1, 'start'),
};