틀린 값은 이유와 함께 막기Refuse bad values with a reason
컬럼마다 규칙(필수, 최대 길이, 범위, 내가 만든 규칙)을 두면, 어긋나는 값은 확정되지 않고 칸에 이유가 나와요. 내가 만든 규칙은 같은 줄의 다른 칸과 비교할 수도 있어요.Put rules on a column (required, max length, range, your own) and a bad value is not committed; the reason shows on the cell. A custom rule can compare with other cells of the same 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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="editName">이름 편집</button>
<button type="button" id="editEmail">이메일 편집</button>
<button type="button" id="editStart">시작 시간 편집</button>
<button type="button" id="editEnd">종료 시간 편집</button>
</div>
<div id="grid" style="height: 270px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('editName').addEventListener('click', () => actions.editName(api));
document.getElementById('editEmail').addEventListener('click', () => actions.editEmail(api));
document.getElementById('editStart').addEventListener('click', () => actions.editStart(api));
document.getElementById('editEnd').addEventListener('click', () => actions.editEnd(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const rows = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', start: 9, end: 17 },
{ id: 2, name: '이준호', email: 'junho@example.com', start: 8, end: 16 },
{ id: 3, name: '박민지', email: 'minji@example.com', start: 10, end: 18 },
{ id: 4, name: '최도윤', email: 'doyun@example.com', start: 13, end: 21 },
];
// 검사는 정해진 순서로 돌아요: 값의 종류 → required → min·max·maxLength → custom(내가 만든 규칙).
// 기본 규칙(required, min, max, maxLength)의 안내 문구는 정해져 있어서, 이 예제는 말투를 맞추려고 모든 규칙을 custom으로 써요.
// 하나라도 어긋나면 확정되지 않고, 편집기가 열린 채로 이유가 칸에 나와요. 고칠 때까지 다른 값은 들어가지 않아요.
export const options = {
columns: [
{
id: 'name',
title: '이름',
width: 100,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name)
return L('이름을 입력해 주세요.', 'Enter a name.');
return name.length > 6
? L('이름은 6글자까지 쓸 수 있어요.', 'A name can be up to 6 characters.')
: null;
},
},
},
{
id: 'email',
title: '이메일',
width: 210,
editable: true,
validation: {
custom: (value) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L('이메일 모양이 아니에요. 예: name@example.com', 'This is not an email address. Example: name@example.com'),
},
},
{
id: 'start',
title: '시작(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
// custom은 같은 줄(row)도 받아서 다른 칸과 비교할 수 있어요. 시작을 늦출 때도 종료보다 빨라야 해요.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23)
return L('시작 시각은 0시부터 23시 사이예요.', 'The start hour must be between 0 and 23.');
return hour < row.end
? null
: L(`종료(${row.end}시)보다 빨라야 해요.`, `Must be earlier than the end (${row.end}).`);
},
},
},
{
id: 'end',
title: '종료(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24)
return L('종료 시각은 0시부터 24시 사이예요.', 'The end hour must be between 0 and 24.');
return hour > row.start
? null
: L(`시작(${row.start}시)보다 늦어야 해요.`, `Must be later than the start (${row.start}).`);
},
},
},
],
rows,
rowKey: 'id',
};
export function setup(api, log) {
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 아래에 눈에 보이는 안내 줄도 둬요.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게).
const setReason = (text) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log({
ko: '값을 일부러 틀리게 써 보세요. 확정되지 않고 이유가 칸 아래와 기록에 나와요.',
en: 'Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.',
});
const offs = [
api.on('validationFailed', (e) => {
const text = L(`${e.rowKey}번 줄 ${title(e.columnId)}: ${e.message}`, `Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`);
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// 취소하면 칸은 원래 값으로 돌아가 다시 올바르니, 남은 이유 줄을 지운다.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log({
ko: `✓ ${e.rowKey}번 줄 ${title(e.columnId)} = ${String(e.newValue)}`,
en: `✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
editName: (api) => api.startEdit(1, 'name'),
editEmail: (api) => api.startEdit(1, 'email'),
editStart: (api) => api.startEdit(1, 'start'),
editEnd: (api) => api.startEdit(1, 'end'),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>틀린 값은 이유와 함께 막기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="editName">이름 편집</button>
<button type="button" id="editEmail">이메일 편집</button>
<button type="button" id="editStart">시작 시간 편집</button>
<button type="button" id="editEnd">종료 시간 편집</button>
</div>
<div id="grid" style="height: 270px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const rows = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', start: 9, end: 17 },
{ id: 2, name: '이준호', email: 'junho@example.com', start: 8, end: 16 },
{ id: 3, name: '박민지', email: 'minji@example.com', start: 10, end: 18 },
{ id: 4, name: '최도윤', email: 'doyun@example.com', start: 13, end: 21 },
];
// 검사는 정해진 순서로 돌아요: 값의 종류 → required → min·max·maxLength → custom(내가 만든 규칙).
// 기본 규칙(required, min, max, maxLength)의 안내 문구는 정해져 있어서, 이 예제는 말투를 맞추려고 모든 규칙을 custom으로 써요.
// 하나라도 어긋나면 확정되지 않고, 편집기가 열린 채로 이유가 칸에 나와요. 고칠 때까지 다른 값은 들어가지 않아요.
const options = {
columns: [
{
id: 'name',
title: '이름',
width: 100,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name)
return L('이름을 입력해 주세요.', 'Enter a name.');
return name.length > 6
? L('이름은 6글자까지 쓸 수 있어요.', 'A name can be up to 6 characters.')
: null;
},
},
},
{
id: 'email',
title: '이메일',
width: 210,
editable: true,
validation: {
custom: (value) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L('이메일 모양이 아니에요. 예: name@example.com', 'This is not an email address. Example: name@example.com'),
},
},
{
id: 'start',
title: '시작(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
// custom은 같은 줄(row)도 받아서 다른 칸과 비교할 수 있어요. 시작을 늦출 때도 종료보다 빨라야 해요.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23)
return L('시작 시각은 0시부터 23시 사이예요.', 'The start hour must be between 0 and 23.');
return hour < row.end
? null
: L(`종료(${row.end}시)보다 빨라야 해요.`, `Must be earlier than the end (${row.end}).`);
},
},
},
{
id: 'end',
title: '종료(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24)
return L('종료 시각은 0시부터 24시 사이예요.', 'The end hour must be between 0 and 24.');
return hour > row.start
? null
: L(`시작(${row.start}시)보다 늦어야 해요.`, `Must be later than the start (${row.start}).`);
},
},
},
],
rows,
rowKey: 'id',
};
function setup(api, log) {
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 아래에 눈에 보이는 안내 줄도 둬요.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게).
const setReason = (text) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log({
ko: '값을 일부러 틀리게 써 보세요. 확정되지 않고 이유가 칸 아래와 기록에 나와요.',
en: 'Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.',
});
const offs = [
api.on('validationFailed', (e) => {
const text = L(`${e.rowKey}번 줄 ${title(e.columnId)}: ${e.message}`, `Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`);
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// 취소하면 칸은 원래 값으로 돌아가 다시 올바르니, 남은 이유 줄을 지운다.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log({
ko: `✓ ${e.rowKey}번 줄 ${title(e.columnId)} = ${String(e.newValue)}`,
en: `✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
const actions = {
editName: (api) => api.startEdit(1, 'name'),
editEmail: (api) => api.startEdit(1, 'email'),
editStart: (api) => api.startEdit(1, 'start'),
editEnd: (api) => api.startEdit(1, 'end'),
};
options.ariaLabel = "틀린 값은 이유와 함께 막기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('editName').addEventListener('click', () => actions.editName(api));
document.getElementById('editEmail').addEventListener('click', () => actions.editEmail(api));
document.getElementById('editStart').addEventListener('click', () => actions.editStart(api));
document.getElementById('editEnd').addEventListener('click', () => actions.editEnd(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.editName(api)}
>이름 편집</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editEmail(api)}
>이메일 편집</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editStart(api)}
>시작 시간 편집</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editEnd(api)}
>종료 시간 편집</button>
</div>
<Grid style={{ height: 270 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
start: number;
end: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', start: 9, end: 17 },
{ id: 2, name: '이준호', email: 'junho@example.com', start: 8, end: 16 },
{ id: 3, name: '박민지', email: 'minji@example.com', start: 10, end: 18 },
{ id: 4, name: '최도윤', email: 'doyun@example.com', start: 13, end: 21 },
];
// 검사는 정해진 순서로 돌아요: 값의 종류 → required → min·max·maxLength → custom(내가 만든 규칙).
// 기본 규칙(required, min, max, maxLength)의 안내 문구는 정해져 있어서, 이 예제는 말투를 맞추려고 모든 규칙을 custom으로 써요.
// 하나라도 어긋나면 확정되지 않고, 편집기가 열린 채로 이유가 칸에 나와요. 고칠 때까지 다른 값은 들어가지 않아요.
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: '이름',
width: 100,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name) return L('이름을 입력해 주세요.', 'Enter a name.');
return name.length > 6
? L('이름은 6글자까지 쓸 수 있어요.', 'A name can be up to 6 characters.')
: null;
},
},
},
{
id: 'email',
title: '이메일',
width: 210,
editable: true,
validation: {
custom: (value) =>
/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L(
'이메일 모양이 아니에요. 예: name@example.com',
'This is not an email address. Example: name@example.com',
),
},
},
{
id: 'start',
title: '시작(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
// custom은 같은 줄(row)도 받아서 다른 칸과 비교할 수 있어요. 시작을 늦출 때도 종료보다 빨라야 해요.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23)
return L(
'시작 시각은 0시부터 23시 사이예요.',
'The start hour must be between 0 and 23.',
);
return hour < row.end
? null
: L(
`종료(${row.end}시)보다 빨라야 해요.`,
`Must be earlier than the end (${row.end}).`,
);
},
},
},
{
id: 'end',
title: '종료(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24)
return L(
'종료 시각은 0시부터 24시 사이예요.',
'The end hour must be between 0 and 24.',
);
return hour > row.start
? null
: L(
`시작(${row.start}시)보다 늦어야 해요.`,
`Must be later than the start (${row.start}).`,
);
},
},
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 아래에 눈에 보이는 안내 줄도 둬요.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게).
const setReason = (text: string) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log({
ko: '값을 일부러 틀리게 써 보세요. 확정되지 않고 이유가 칸 아래와 기록에 나와요.',
en: 'Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.',
});
const offs = [
api.on('validationFailed', (e) => {
const text = L(
`${e.rowKey}번 줄 ${title(e.columnId)}: ${e.message}`,
`Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`,
);
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// 취소하면 칸은 원래 값으로 돌아가 다시 올바르니, 남은 이유 줄을 지운다.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log({
ko: `✓ ${e.rowKey}번 줄 ${title(e.columnId)} = ${String(e.newValue)}`,
en: `✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
editName: (api: GridApi<Row>) => api.startEdit(1, 'name'),
editEmail: (api: GridApi<Row>) => api.startEdit(1, 'email'),
editStart: (api: GridApi<Row>) => api.startEdit(1, 'start'),
editEnd: (api: GridApi<Row>) => api.startEdit(1, 'end'),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.editName(api)"
>이름 편집</button>
<button
type="button"
:disabled="!api"
@click="api && actions.editEmail(api)"
>이메일 편집</button>
<button
type="button"
:disabled="!api"
@click="api && actions.editStart(api)"
>시작 시간 편집</button>
<button type="button" :disabled="!api" @click="api && actions.editEnd(api)">종료 시간 편집</button>
</div>
<Grid style="height: 270px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
start: number;
end: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', start: 9, end: 17 },
{ id: 2, name: '이준호', email: 'junho@example.com', start: 8, end: 16 },
{ id: 3, name: '박민지', email: 'minji@example.com', start: 10, end: 18 },
{ id: 4, name: '최도윤', email: 'doyun@example.com', start: 13, end: 21 },
];
// 검사는 정해진 순서로 돌아요: 값의 종류 → required → min·max·maxLength → custom(내가 만든 규칙).
// 기본 규칙(required, min, max, maxLength)의 안내 문구는 정해져 있어서, 이 예제는 말투를 맞추려고 모든 규칙을 custom으로 써요.
// 하나라도 어긋나면 확정되지 않고, 편집기가 열린 채로 이유가 칸에 나와요. 고칠 때까지 다른 값은 들어가지 않아요.
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: '이름',
width: 100,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name) return L('이름을 입력해 주세요.', 'Enter a name.');
return name.length > 6
? L('이름은 6글자까지 쓸 수 있어요.', 'A name can be up to 6 characters.')
: null;
},
},
},
{
id: 'email',
title: '이메일',
width: 210,
editable: true,
validation: {
custom: (value) =>
/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L(
'이메일 모양이 아니에요. 예: name@example.com',
'This is not an email address. Example: name@example.com',
),
},
},
{
id: 'start',
title: '시작(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
// custom은 같은 줄(row)도 받아서 다른 칸과 비교할 수 있어요. 시작을 늦출 때도 종료보다 빨라야 해요.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23)
return L(
'시작 시각은 0시부터 23시 사이예요.',
'The start hour must be between 0 and 23.',
);
return hour < row.end
? null
: L(
`종료(${row.end}시)보다 빨라야 해요.`,
`Must be earlier than the end (${row.end}).`,
);
},
},
},
{
id: 'end',
title: '종료(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24)
return L(
'종료 시각은 0시부터 24시 사이예요.',
'The end hour must be between 0 and 24.',
);
return hour > row.start
? null
: L(
`시작(${row.start}시)보다 늦어야 해요.`,
`Must be later than the start (${row.start}).`,
);
},
},
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 아래에 눈에 보이는 안내 줄도 둬요.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게).
const setReason = (text: string) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log({
ko: '값을 일부러 틀리게 써 보세요. 확정되지 않고 이유가 칸 아래와 기록에 나와요.',
en: 'Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.',
});
const offs = [
api.on('validationFailed', (e) => {
const text = L(
`${e.rowKey}번 줄 ${title(e.columnId)}: ${e.message}`,
`Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`,
);
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// 취소하면 칸은 원래 값으로 돌아가 다시 올바르니, 남은 이유 줄을 지운다.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log({
ko: `✓ ${e.rowKey}번 줄 ${title(e.columnId)} = ${String(e.newValue)}`,
en: `✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
editName: (api: GridApi<Row>) => api.startEdit(1, 'name'),
editEmail: (api: GridApi<Row>) => api.startEdit(1, 'email'),
editStart: (api: GridApi<Row>) => api.startEdit(1, 'start'),
editEnd: (api: GridApi<Row>) => api.startEdit(1, 'end'),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.editName(api)"
>이름 편집</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editEmail(api)"
>이메일 편집</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editStart(api)"
>시작 시간 편집</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editEnd(api)"
>종료 시간 편집</button>
</div>
<mx-grid style="height: 270px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
start: number;
end: number;
}
const rows: Row[] = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', start: 9, end: 17 },
{ id: 2, name: '이준호', email: 'junho@example.com', start: 8, end: 16 },
{ id: 3, name: '박민지', email: 'minji@example.com', start: 10, end: 18 },
{ id: 4, name: '최도윤', email: 'doyun@example.com', start: 13, end: 21 },
];
// 검사는 정해진 순서로 돌아요: 값의 종류 → required → min·max·maxLength → custom(내가 만든 규칙).
// 기본 규칙(required, min, max, maxLength)의 안내 문구는 정해져 있어서, 이 예제는 말투를 맞추려고 모든 규칙을 custom으로 써요.
// 하나라도 어긋나면 확정되지 않고, 편집기가 열린 채로 이유가 칸에 나와요. 고칠 때까지 다른 값은 들어가지 않아요.
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: '이름',
width: 100,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name) return L('이름을 입력해 주세요.', 'Enter a name.');
return name.length > 6
? L('이름은 6글자까지 쓸 수 있어요.', 'A name can be up to 6 characters.')
: null;
},
},
},
{
id: 'email',
title: '이메일',
width: 210,
editable: true,
validation: {
custom: (value) =>
/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L(
'이메일 모양이 아니에요. 예: name@example.com',
'This is not an email address. Example: name@example.com',
),
},
},
{
id: 'start',
title: '시작(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
// custom은 같은 줄(row)도 받아서 다른 칸과 비교할 수 있어요. 시작을 늦출 때도 종료보다 빨라야 해요.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23)
return L(
'시작 시각은 0시부터 23시 사이예요.',
'The start hour must be between 0 and 23.',
);
return hour < row.end
? null
: L(
`종료(${row.end}시)보다 빨라야 해요.`,
`Must be earlier than the end (${row.end}).`,
);
},
},
},
{
id: 'end',
title: '종료(시)',
kind: 'number',
width: 100,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24)
return L(
'종료 시각은 0시부터 24시 사이예요.',
'The end hour must be between 0 and 24.',
);
return hour > row.start
? null
: L(
`시작(${row.start}시)보다 늦어야 해요.`,
`Must be later than the start (${row.start}).`,
);
},
},
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 이유를 마우스를 올려야만 보이면 터치·키보드로는 놓쳐요. 표 아래에 눈에 보이는 안내 줄도 둬요.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// 안내가 없을 때는 자리를 차지하지 않는다(표와 로그 사이가 벌어져 보이지 않게).
const setReason = (text: string) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log({
ko: '값을 일부러 틀리게 써 보세요. 확정되지 않고 이유가 칸 아래와 기록에 나와요.',
en: 'Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.',
});
const offs = [
api.on('validationFailed', (e) => {
const text = L(
`${e.rowKey}번 줄 ${title(e.columnId)}: ${e.message}`,
`Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`,
);
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// 취소하면 칸은 원래 값으로 돌아가 다시 올바르니, 남은 이유 줄을 지운다.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log({
ko: `✓ ${e.rowKey}번 줄 ${title(e.columnId)} = ${String(e.newValue)}`,
en: `✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`,
});
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
editName: (api: GridApi<Row>) => api.startEdit(1, 'name'),
editEmail: (api: GridApi<Row>) => api.startEdit(1, 'email'),
editStart: (api: GridApi<Row>) => api.startEdit(1, 'start'),
editEnd: (api: GridApi<Row>) => api.startEdit(1, 'end'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="editName">Edit name</button>
<button type="button" id="editEmail">Edit email</button>
<button type="button" id="editStart">Edit start</button>
<button type="button" id="editEnd">Edit end</button>
</div>
<div id="grid" style="height: 270px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('editName').addEventListener('click', () => actions.editName(api));
document.getElementById('editEmail').addEventListener('click', () => actions.editEmail(api));
document.getElementById('editStart').addEventListener('click', () => actions.editStart(api));
document.getElementById('editEnd').addEventListener('click', () => actions.editEnd(api));// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko, en) => en;
const rows = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', start: 9, end: 17 },
{ id: 2, name: 'Emma Stone', email: 'emma@example.com', start: 8, end: 16 },
{ id: 3, name: 'Olivia Park', email: 'olivia@example.com', start: 10, end: 18 },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', start: 13, end: 21 },
];
// Checks run in a fixed order: value kind -> required -> min/max/maxLength -> custom (your own rule).
// The default rules (required, min, max, maxLength) have fixed messages, so this example uses custom for every rule to keep the tone consistent.
// If any check fails the value is not committed, and the editor stays open with the reason shown on the cell. No other value is accepted until it is fixed.
export const options = {
columns: [
{
id: 'name',
title: 'Name',
width: 130,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name)
return L('', 'Enter a name.');
return name.length > 6 ? L('', 'A name can be up to 6 characters.') : null;
},
},
},
{
id: 'email',
title: 'Email',
width: 210,
editable: true,
validation: {
custom: (value) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L('', 'This is not an email address. Example: name@example.com'),
},
},
{
id: 'start',
title: 'Start (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
// custom also receives the same row, so it can compare with other cells. Even when the start is moved later, it must stay earlier than the end.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23)
return L('', 'The start hour must be between 0 and 23.');
return hour < row.end ? null : L('', `Must be earlier than the end (${row.end}).`);
},
},
},
{
id: 'end',
title: 'End (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24)
return L('', 'The end hour must be between 0 and 24.');
return hour > row.start ? null : L('', `Must be later than the start (${row.start}).`);
},
},
},
],
rows,
rowKey: 'id',
};
export function setup(api, log) {
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// A reason visible only on hover is missed by touch and keyboard users, so also show a visible message line under the grid.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// When there is no message it takes no space (so the gap between the grid and the log does not look wide).
const setReason = (text) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log('Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.');
const offs = [
api.on('validationFailed', (e) => {
const text = `Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`;
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// On cancel the cell returns to its original value and is valid again, so clear the leftover message line.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log(`✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
editName: (api) => api.startEdit(1, 'name'),
editEmail: (api) => api.startEdit(1, 'email'),
editStart: (api) => api.startEdit(1, 'start'),
editEnd: (api) => api.startEdit(1, 'end'),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Refuse bad values with a reason</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="editName">Edit name</button>
<button type="button" id="editEmail">Edit email</button>
<button type="button" id="editStart">Edit start</button>
<button type="button" id="editEnd">Edit end</button>
</div>
<div id="grid" style="height: 270px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko, en) => en;
const rows = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', start: 9, end: 17 },
{ id: 2, name: 'Emma Stone', email: 'emma@example.com', start: 8, end: 16 },
{ id: 3, name: 'Olivia Park', email: 'olivia@example.com', start: 10, end: 18 },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', start: 13, end: 21 },
];
// Checks run in a fixed order: value kind -> required -> min/max/maxLength -> custom (your own rule).
// The default rules (required, min, max, maxLength) have fixed messages, so this example uses custom for every rule to keep the tone consistent.
// If any check fails the value is not committed, and the editor stays open with the reason shown on the cell. No other value is accepted until it is fixed.
const options = {
columns: [
{
id: 'name',
title: 'Name',
width: 130,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name)
return L('', 'Enter a name.');
return name.length > 6 ? L('', 'A name can be up to 6 characters.') : null;
},
},
},
{
id: 'email',
title: 'Email',
width: 210,
editable: true,
validation: {
custom: (value) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L('', 'This is not an email address. Example: name@example.com'),
},
},
{
id: 'start',
title: 'Start (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
// custom also receives the same row, so it can compare with other cells. Even when the start is moved later, it must stay earlier than the end.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23)
return L('', 'The start hour must be between 0 and 23.');
return hour < row.end ? null : L('', `Must be earlier than the end (${row.end}).`);
},
},
},
{
id: 'end',
title: 'End (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24)
return L('', 'The end hour must be between 0 and 24.');
return hour > row.start ? null : L('', `Must be later than the start (${row.start}).`);
},
},
},
],
rows,
rowKey: 'id',
};
function setup(api, log) {
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// A reason visible only on hover is missed by touch and keyboard users, so also show a visible message line under the grid.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// When there is no message it takes no space (so the gap between the grid and the log does not look wide).
const setReason = (text) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log('Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.');
const offs = [
api.on('validationFailed', (e) => {
const text = `Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`;
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// On cancel the cell returns to its original value and is valid again, so clear the leftover message line.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log(`✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
const actions = {
editName: (api) => api.startEdit(1, 'name'),
editEmail: (api) => api.startEdit(1, 'email'),
editStart: (api) => api.startEdit(1, 'start'),
editEnd: (api) => api.startEdit(1, 'end'),
};
options.ariaLabel = "Refuse bad values with a reason";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('editName').addEventListener('click', () => actions.editName(api));
document.getElementById('editEmail').addEventListener('click', () => actions.editEmail(api));
document.getElementById('editStart').addEventListener('click', () => actions.editStart(api));
document.getElementById('editEnd').addEventListener('click', () => actions.editEnd(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.editName(api)}
>Edit name</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editEmail(api)}
>Edit email</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editStart(api)}
>Edit start</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.editEnd(api)}
>Edit end</button>
</div>
<Grid style={{ height: 270 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko: string, en: string): string => en;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
start: number;
end: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', start: 9, end: 17 },
{ id: 2, name: 'Emma Stone', email: 'emma@example.com', start: 8, end: 16 },
{ id: 3, name: 'Olivia Park', email: 'olivia@example.com', start: 10, end: 18 },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', start: 13, end: 21 },
];
// Checks run in a fixed order: value kind -> required -> min/max/maxLength -> custom (your own rule).
// The default rules (required, min, max, maxLength) have fixed messages, so this example uses custom for every rule to keep the tone consistent.
// If any check fails the value is not committed, and the editor stays open with the reason shown on the cell. No other value is accepted until it is fixed.
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: 'Name',
width: 130,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name) return L('', 'Enter a name.');
return name.length > 6 ? L('', 'A name can be up to 6 characters.') : null;
},
},
},
{
id: 'email',
title: 'Email',
width: 210,
editable: true,
validation: {
custom: (value) =>
/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L('', 'This is not an email address. Example: name@example.com'),
},
},
{
id: 'start',
title: 'Start (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
// custom also receives the same row, so it can compare with other cells. Even when the start is moved later, it must stay earlier than the end.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23) return L('', 'The start hour must be between 0 and 23.');
return hour < row.end ? null : L('', `Must be earlier than the end (${row.end}).`);
},
},
},
{
id: 'end',
title: 'End (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24) return L('', 'The end hour must be between 0 and 24.');
return hour > row.start ? null : L('', `Must be later than the start (${row.start}).`);
},
},
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// A reason visible only on hover is missed by touch and keyboard users, so also show a visible message line under the grid.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// When there is no message it takes no space (so the gap between the grid and the log does not look wide).
const setReason = (text: string) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log(
'Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.',
);
const offs = [
api.on('validationFailed', (e) => {
const text = `Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`;
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// On cancel the cell returns to its original value and is valid again, so clear the leftover message line.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log(`✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
editName: (api: GridApi<Row>) => api.startEdit(1, 'name'),
editEmail: (api: GridApi<Row>) => api.startEdit(1, 'email'),
editStart: (api: GridApi<Row>) => api.startEdit(1, 'start'),
editEnd: (api: GridApi<Row>) => api.startEdit(1, 'end'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.editName(api)"
>Edit name</button>
<button
type="button"
:disabled="!api"
@click="api && actions.editEmail(api)"
>Edit email</button>
<button
type="button"
:disabled="!api"
@click="api && actions.editStart(api)"
>Edit start</button>
<button type="button" :disabled="!api" @click="api && actions.editEnd(api)">Edit end</button>
</div>
<Grid style="height: 270px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko: string, en: string): string => en;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
start: number;
end: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', start: 9, end: 17 },
{ id: 2, name: 'Emma Stone', email: 'emma@example.com', start: 8, end: 16 },
{ id: 3, name: 'Olivia Park', email: 'olivia@example.com', start: 10, end: 18 },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', start: 13, end: 21 },
];
// Checks run in a fixed order: value kind -> required -> min/max/maxLength -> custom (your own rule).
// The default rules (required, min, max, maxLength) have fixed messages, so this example uses custom for every rule to keep the tone consistent.
// If any check fails the value is not committed, and the editor stays open with the reason shown on the cell. No other value is accepted until it is fixed.
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: 'Name',
width: 130,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name) return L('', 'Enter a name.');
return name.length > 6 ? L('', 'A name can be up to 6 characters.') : null;
},
},
},
{
id: 'email',
title: 'Email',
width: 210,
editable: true,
validation: {
custom: (value) =>
/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L('', 'This is not an email address. Example: name@example.com'),
},
},
{
id: 'start',
title: 'Start (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
// custom also receives the same row, so it can compare with other cells. Even when the start is moved later, it must stay earlier than the end.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23) return L('', 'The start hour must be between 0 and 23.');
return hour < row.end ? null : L('', `Must be earlier than the end (${row.end}).`);
},
},
},
{
id: 'end',
title: 'End (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24) return L('', 'The end hour must be between 0 and 24.');
return hour > row.start ? null : L('', `Must be later than the start (${row.start}).`);
},
},
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// A reason visible only on hover is missed by touch and keyboard users, so also show a visible message line under the grid.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// When there is no message it takes no space (so the gap between the grid and the log does not look wide).
const setReason = (text: string) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log(
'Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.',
);
const offs = [
api.on('validationFailed', (e) => {
const text = `Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`;
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// On cancel the cell returns to its original value and is valid again, so clear the leftover message line.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log(`✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
editName: (api: GridApi<Row>) => api.startEdit(1, 'name'),
editEmail: (api: GridApi<Row>) => api.startEdit(1, 'email'),
editStart: (api: GridApi<Row>) => api.startEdit(1, 'start'),
editEnd: (api: GridApi<Row>) => api.startEdit(1, 'end'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.editName(api)"
>Edit name</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editEmail(api)"
>Edit email</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editStart(api)"
>Edit start</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.editEnd(api)"
>Edit end</button>
</div>
<mx-grid style="height: 270px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
// Picks the message for the page language (this English sample always uses the en text).
const L = (_ko: string, en: string): string => en;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
start: number;
end: number;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', start: 9, end: 17 },
{ id: 2, name: 'Emma Stone', email: 'emma@example.com', start: 8, end: 16 },
{ id: 3, name: 'Olivia Park', email: 'olivia@example.com', start: 10, end: 18 },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', start: 13, end: 21 },
];
// Checks run in a fixed order: value kind -> required -> min/max/maxLength -> custom (your own rule).
// The default rules (required, min, max, maxLength) have fixed messages, so this example uses custom for every rule to keep the tone consistent.
// If any check fails the value is not committed, and the editor stays open with the reason shown on the cell. No other value is accepted until it is fixed.
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: 'Name',
width: 130,
editable: true,
validation: {
custom: (value) => {
const name = String(value).trim();
if (!name) return L('', 'Enter a name.');
return name.length > 6 ? L('', 'A name can be up to 6 characters.') : null;
},
},
},
{
id: 'email',
title: 'Email',
width: 210,
editable: true,
validation: {
custom: (value) =>
/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(value))
? null
: L('', 'This is not an email address. Example: name@example.com'),
},
},
{
id: 'start',
title: 'Start (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
// custom also receives the same row, so it can compare with other cells. Even when the start is moved later, it must stay earlier than the end.
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 23) return L('', 'The start hour must be between 0 and 23.');
return hour < row.end ? null : L('', `Must be earlier than the end (${row.end}).`);
},
},
},
{
id: 'end',
title: 'End (hour)',
kind: 'number',
width: 110,
align: 'end',
editable: true,
validation: {
custom: (value, row) => {
const hour = Number(value);
if (hour < 0 || hour > 24) return L('', 'The end hour must be between 0 and 24.');
return hour > row.start ? null : L('', `Must be later than the start (${row.start}).`);
},
},
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const title = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// A reason visible only on hover is missed by touch and keyboard users, so also show a visible message line under the grid.
const reason = document.createElement('div');
reason.setAttribute('role', 'status');
reason.style.cssText =
'margin-top: 0; font-size: 13px; color: color-mix(in srgb, #e5484d 75%, var(--fg));';
// When there is no message it takes no space (so the gap between the grid and the log does not look wide).
const setReason = (text: string) => {
reason.textContent = text;
reason.style.marginTop = text ? '6px' : '0';
};
document.getElementById('grid')?.after(reason);
log(
'Type a wrong value on purpose. It is not confirmed, and the reason shows under the cell and in the log.',
);
const offs = [
api.on('validationFailed', (e) => {
const text = `Row ${e.rowKey} ${title(e.columnId)}: ${e.message}`;
setReason(`✗ ${text}`);
log(`✗ ${text}`);
}),
// On cancel the cell returns to its original value and is valid again, so clear the leftover message line.
api.on('editCancelled', () => setReason('')),
api.on('editCommitted', (e) => {
setReason('');
log(`✓ Row ${e.rowKey} ${title(e.columnId)} = ${String(e.newValue)}`);
}),
];
return () => {
offs.forEach((off) => off());
reason.remove();
};
}
export const actions = {
editName: (api: GridApi<Row>) => api.startEdit(1, 'name'),
editEmail: (api: GridApi<Row>) => api.startEdit(1, 'email'),
editStart: (api: GridApi<Row>) => api.startEdit(1, 'start'),
editEnd: (api: GridApi<Row>) => api.startEdit(1, 'end'),
};