예제
실용적인 예제와 라이브 데모.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
검증 규칙은 평범한 상태를 들여다보는 함수입니다. 사용자가 건드린 필드에만 오류를 보여 주고, debounce를 건 비동기 검사에는 진행 중 상태를 표시하며, 제출은 이 모든 검사가 끝나기를 기다립니다.
import 'nuclo' const values = { username: '', email: '', password: '', confirm: '' } const touched = new Set<keyof typeof values>() let availability: 'idle' | 'checking' | 'taken' | 'free' = 'idle' let submitted: string | null = null const taken = ['ada', 'grace', 'linus'] // stands in for a server // Validation is a plain function over the state. It runs on every // update(), so the messages are always current. const errors = () => ({ username: values.username.length < 3 ? 'At least 3 characters' : availability === 'taken' ? 'Already taken' : null, email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email) ? null : 'Enter a valid email', password: values.password.length < 8 ? 'At least 8 characters' : !/\d/.test(values.password) ? 'Include a number' : null, confirm: values.confirm === values.password ? null : 'Passwords do not match', }) const valid = () => Object.values(errors()).every((e) => e === null) && availability !== 'checking' // An async check: debounced, with a pending state the UI can show. let timer: ReturnType<typeof setTimeout> function checkUsername() { clearTimeout(timer) if (values.username.length < 3) { availability = 'idle'; return } availability = 'checking' timer = setTimeout(() => { availability = taken.includes(values.username.toLowerCase()) ? 'taken' : 'free' update() }, 500) } // A field shows its error only once it was touched (blurred): // red while invalid, green once it passes. function Field( key: keyof typeof values, text: string, type = 'text', placeholder = '', hint: () => string = () => '', ) { const show = () => touched.has(key) && errors()[key] const ok = () => touched.has(key) && !errors()[key] return div( label(text, ' ', small(hint)), input({ type, placeholder, value: () => values[key], style: () => ({ borderColor: show() ? '#ef4444' : ok() ? '#22c55e' : '' }), 'aria-invalid': () => String(!!show()), onInput: (e) => { values[key] = e.currentTarget.value if (key === 'username') checkUsername() update() }, onBlur: () => { touched.add(key); update() }, }), p({ role: 'alert' }, () => show() || ''), ) } export const SignUp = () => form( Field('username', 'Username', 'text', 'ada, grace and linus are taken', () => availability === 'checking' ? 'checking…' : availability === 'free' ? 'available' : ''), Field('email', 'Email', 'email', '[email protected]'), Field('password', 'Password', 'password', '8+ characters, one number'), Field('confirm', 'Confirm password', 'password'), div( // Disabled until every rule passes and the async check is done. button('Create account', { type: 'button', disabled: () => !valid(), onClick: () => { submitted = JSON.stringify({ username: values.username, email: values.email }) update() }, }), small(() => (valid() ? '' : 'Fix the fields above')), ), when(() => submitted !== null, p('Submitted ', code(() => submitted ?? ''))), )