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

저장하기 전에 빈 필수 칸 점검Check required cells before saving

처음부터 비어 있던 칸은 고치지 않으면 검사되지 않아요. 그래서 모든 줄을 훑어 빈 칸을 컬럼별로 모아 보여 주고, 저장(save)은 바뀐 줄 전부를 검사해서 하나라도 틀리면 아무것도 보내지 않게 했어요.Cells that start empty are not checked until someone edits them. So scan every row and group the gaps per column, and let save() validate all changed rows and send nothing if one is wrong.

활용Intermediate
직접 써 보기Live preview저장하기 전에 빈 필수 칸 점검Check required cells before saving

코드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="scan">빈 칸 점검</button>
    <button type="button" id="firstGap">첫 빈 칸으로</button>
    <button type="button" id="addEmpty">빈 새 줄 넣기</button>
    <button type="button" id="save">저장</button>
    <button type="button" id="discard">변경 버리기</button>
  </div>
  <div id="grid" style="height: 300px"></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('scan').addEventListener('click', () => actions.scan(api));
document.getElementById('firstGap').addEventListener('click', () => actions.firstGap(api));
document.getElementById('addEmpty').addEventListener('click', () => actions.addEmpty(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
example.js
const rows = [
  { id: 1, name: '김서연', email: 'seoyeon@example.com', team: '개발' },
  { id: 2, name: '이준호', email: '', team: '디자인' },
  { id: 3, name: '', email: '', team: '' },
  { id: 4, name: '최도윤', email: 'doyun@example.com', team: '기획' },
];
const FIELDS = ['name', 'email', 'team'];
const label = { name: '이름', email: '이메일', team: '팀' };
const labelEn = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say = () => { };
// 비어 있는 필수 칸은 눈에 띄게 표시해요(CSS 변수라서 밝은·어두운 테마 모두 맞아요).
const emptyMark = (ctx) => String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options = {
  columns: [
    {
      id: 'name',
      title: '이름 *',
      width: 120,
      editable: true,
      validation: { required: true },
      cellClass: emptyMark,
    },
    {
      id: 'email',
      title: '이메일 *',
      width: 210,
      editable: true,
      validation: { required: true },
      cellClass: emptyMark,
    },
    {
      id: 'team',
      title: '팀 *',
      width: 110,
      editable: true,
      validation: { required: true },
      cellClass: emptyMark,
    },
  ],
  rows,
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: async () => {
    await new Promise((resolve) => setTimeout(resolve, 300)); // 서버에 보내는 시간을 흉내 내요.
  },
};
// 필수 칸은 "고칠 때"만 검사돼요. 처음부터 비어 있던 칸은 아무도 안 건드렸으니 검사되지 않아요.
// 그래서 저장하기 전에 모든 줄을 훑어서 빈 칸을 컬럼별로 모아 보여 줘요(내가 짠 점검 함수예요).
function gaps(api) {
  return api
    .getRows()
    .flatMap((row) => FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })));
}
export function setup(api, log) {
  say = log;
  const found = gaps(api);
  log({
    ko: found.length
      ? `빈 칸이 ${found.length}개 있어요. "빈 칸 점검"으로 어디인지 확인해 보세요.`
      : '모든 필수 칸이 채워져 있어요.',
    en: found.length
      ? `${found.length} empty cells. Use "Check empty cells" to see where.`
      : 'All required cells are filled.',
  });
  return api.on('validationFailed', (e) => log({
    ko: `✗ ${e.rowKey}번 줄 ${label[e.columnId] ?? e.columnId}: ${e.message}`,
    en: `✗ Row ${e.rowKey} ${labelEn[e.columnId] ?? e.columnId}: ${e.message}`,
  }));
}
export const actions = {
  scan: (api) => {
    const found = gaps(api);
    if (!found.length)
      return say({ ko: '✓ 빈 칸이 없어요.', en: '✓ No empty cells.' });
    const byField = FIELDS.map((f) => [f, found.filter((g) => g.field === f).map((g) => g.key)]).filter(([, keys]) => keys.length);
    say({
      ko: `빈 칸 ${found.length}개 → ${byField.map(([f, keys]) => `${label[f]}: ${keys.join(', ')}번 줄`).join(' / ')}`,
      en: `${found.length} empty cells → ${byField.map(([f, keys]) => `${labelEn[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
    });
  },
  firstGap: (api) => {
    const first = gaps(api)[0];
    if (!first)
      return say({ ko: '✓ 비어 있는 칸이 없어요.', en: '✓ No empty cells.' });
    api.startEdit(first.key, first.field);
  },
  // save()는 바뀐 줄 전부를 먼저 검사하고, 하나라도 틀리면 아무것도 보내지 않아요.
  addEmpty: (api) => {
    nextId += 1;
    api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
    say({
      ko: `빈 새 줄(${nextId}번)을 맨 위에 넣었어요. 이제 저장해 보세요.`,
      en: `Put an empty new row (${nextId}) at the top. Now try saving.`,
    });
  },
  save: async (api) => {
    const report = await api.save();
    say({
      ko: report.status === 'invalid'
        ? '값이 맞지 않아 저장하지 않았어요. 아래 ✗ 줄에서 이유를 확인해 주세요.'
        : report.status === 'empty'
          ? '저장할 변경이 없어요. (처음부터 비어 있던 칸은 고친 것이 아니라서 변경에 들어가지 않아요)'
          : report.status === 'saved'
            ? `모두 저장했어요. (${report.committed}줄)`
            : `저장 결과를 확인해 주세요. (${report.status})`,
      en: report.status === 'invalid'
        ? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
        : report.status === 'empty'
          ? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
          : report.status === 'saved'
            ? `All saved. (${report.committed} rows)`
            : `Check the save result. (${report.status})`,
    });
  },
  discard: (api) => api.rollbackChanges(),
};

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="scan">Scan empty cells</button>
    <button type="button" id="firstGap">Go to first gap</button>
    <button type="button" id="addEmpty">Add empty row</button>
    <button type="button" id="save">Save</button>
    <button type="button" id="discard">Discard changes</button>
  </div>
  <div id="grid" style="height: 300px"></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('scan').addEventListener('click', () => actions.scan(api));
document.getElementById('firstGap').addEventListener('click', () => actions.firstGap(api));
document.getElementById('addEmpty').addEventListener('click', () => actions.addEmpty(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
example.js
const rows = [
  { id: 1, name: 'Liam Carter', email: 'liam@example.com', team: 'Dev' },
  { id: 2, name: 'Emma Stone', email: '', team: 'Design' },
  { id: 3, name: '', email: '', team: '' },
  { id: 4, name: 'Noah Kim', email: 'noah@example.com', team: 'Planning' },
];
const FIELDS = ['name', 'email', 'team'];
const label = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say = () => { };
// Empty required cells are marked visibly (it uses CSS variables, so it fits both light and dark themes).
const emptyMark = (ctx) => String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options = {
  columns: [
    {
      id: 'name',
      title: 'Name *',
      width: 140,
      editable: true,
      validation: { required: true },
      cellClass: emptyMark,
    },
    {
      id: 'email',
      title: 'Email *',
      width: 210,
      editable: true,
      validation: { required: true },
      cellClass: emptyMark,
    },
    {
      id: 'team',
      title: 'Team *',
      width: 110,
      editable: true,
      validation: { required: true },
      cellClass: emptyMark,
    },
  ],
  rows,
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: async () => {
    await new Promise((resolve) => setTimeout(resolve, 300)); // Simulates the time it takes to send to a server.
  },
};
// A required cell is only checked when it is edited. A cell that was empty from the start was never touched, so it is not checked.
// So before saving, scan every row and gather the empty cells by column (this is a check function written by the app).
function gaps(api) {
  return api
    .getRows()
    .flatMap((row) => FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })));
}
export function setup(api, log) {
  say = log;
  const found = gaps(api);
  log(found.length
    ? `${found.length} empty cells. Use "Scan empty cells" to see where.`
    : 'All required cells are filled.');
  return api.on('validationFailed', (e) => log(`✗ Row ${e.rowKey} ${label[e.columnId] ?? e.columnId}: ${e.message}`));
}
export const actions = {
  scan: (api) => {
    const found = gaps(api);
    if (!found.length)
      return say('✓ No empty cells.');
    const byField = FIELDS.map((f) => [f, found.filter((g) => g.field === f).map((g) => g.key)]).filter(([, keys]) => keys.length);
    say(`${found.length} empty cells → ${byField.map(([f, keys]) => `${label[f]}: rows ${keys.join(', ')}`).join(' / ')}`);
  },
  firstGap: (api) => {
    const first = gaps(api)[0];
    if (!first)
      return say('✓ No empty cells.');
    api.startEdit(first.key, first.field);
  },
  // save() checks every changed row first, and sends nothing if even one is wrong.
  addEmpty: (api) => {
    nextId += 1;
    api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
    say(`Put an empty new row (${nextId}) at the top. Now try saving.`);
  },
  save: async (api) => {
    const report = await api.save();
    say(report.status === 'invalid'
      ? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
      : report.status === 'empty'
        ? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
        : report.status === 'saved'
          ? `All saved. (${report.committed} rows)`
          : `Check the save result. (${report.status})`);
  },
  discard: (api) => api.rollbackChanges(),
};