formhero/examples/errorsAndValidation.tsx

58 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

2019-09-28 15:20:56 +00:00
import React from 'react'
import { useForm } from '../'
2023-01-31 00:26:27 +00:00
import { mount } from './common'
2019-09-28 15:20:56 +00:00
const Index: React.FC = () => {
2019-10-19 06:45:14 +00:00
const { field, form, errors, isValid } = useForm(
{
username: '',
email: '',
password: '',
},
{
2023-01-31 00:26:27 +00:00
rules: {
username: (value) => value.length > 3,
email: {
rule: /@/,
message: 'Must contain an @',
2019-10-19 06:45:14 +00:00
},
2023-01-31 00:26:27 +00:00
password: [
{
rule: /[A-Z]/,
message: 'Must contain an uppercase letter',
},
{
rule: /[\d]/,
message: 'Must contain a digit',
},
],
},
2019-10-19 06:45:14 +00:00
}
)
return (
<form
2023-01-31 00:26:27 +00:00
onSubmit={(e) => {
2019-10-19 06:45:14 +00:00
e.preventDefault()
if (isValid) console.log(form)
}}
>
<h1>Errors & Validation</h1>
<input {...field('username')} placeholder="Username" />
{errors.username && 'Must be longer than 3'}
<input {...field('email')} placeholder="EMail" />
{errors.email}
<input {...field('password')} placeholder="Password" type="password" />
{errors.password}
<input type="submit" />
</form>
)
2019-09-28 15:20:56 +00:00
}
2023-01-31 00:26:27 +00:00
mount(Index)