Skip to content

Instantly share code, notes, and snippets.

@tatsuyasusukida
Created August 4, 2022 08:09
Show Gist options
  • Save tatsuyasusukida/a2928bb18388ee9c3327c3e59c8d6214 to your computer and use it in GitHub Desktop.
Save tatsuyasusukida/a2928bb18388ee9c3327c3e59c8d6214 to your computer and use it in GitHub Desktop.
πŸ“ How to make a form without react hook form
import { useState } from "react"
import { makeValidationProfile, validateProfile } from "../lib/validate"
export default function Form () {
const [form, setForm] = useState({first: '', last: ''})
const [validation, setValidation] = useState(makeValidationProfile)
const onSubmit = (event: any) => {
event.preventDefault()
const req = {body: {form}}
const validation = validateProfile(req)
setValidation(validation)
console.info(JSON.stringify(validation, null, 2))
}
const onChange = (key: string) => (event: any) => {
const value = {...form, [key]: event.target.value}
setForm(value)
console.info(JSON.stringify(value, null, 2))
}
return (
<form onSubmit={onSubmit}>
<div>
<label htmlFor="first">First name:</label>
<input type="text" id="first" name="first" value={form.first} onChange={onChange('first')} />
<p>
{validation.first.isNotEmpty === false
&& 'First name is empty'}
</p>
</div>
<div>
<label htmlFor="last">Last name:</label>
<input type="text" id="last" name="last" value={form.last} onChange={onChange('last')} />
<p>
{validation.last.isNotEmpty === false
&& 'Last name is empty'}
</p>
</div>
<button type="submit">Submit</button>
</form>
)
}
export function makeValidationProfile () {
return {
ok: null,
first: {ok: null, isNotEmpty: null},
last: {ok: null, isNotEmpty: null},
}
}
export function validateProfile (req) {
const validation = makeValidationProfile()
const {form} = req.body
validation.first.isNotEmpty = !/^\s*$/.test(form.first)
validation.first.ok = validation.first.isNotEmpty === true
validation.last.isNotEmpty = !/^\s*$/.test(form.last)
validation.last.ok = validation.last.isNotEmpty === true
validation.ok = validation.first.ok && validation.last.ok
return validation
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment