formhero/examples/errorsAndValidation.tsx

53 lines
1020 B
TypeScript
Raw Normal View History

2019-09-28 15:20:56 +00:00
import React from 'react'
import ReactDOM from 'react-dom'
import { useForm } from '../'
const Index: React.FC = () => {
2019-09-28 18:14:02 +00:00
const { auto, form, errors, isValid } = useForm({
2019-09-28 15:20:56 +00:00
username: '',
2019-09-28 17:00:49 +00:00
email: '',
2019-09-28 15:20:56 +00:00
password: ''
}, {
username: value => value.length > 3,
2019-09-28 17:00:49 +00:00
email: {
validator: /@/,
message: 'Must contain an @',
},
password: [
{
validator: /[A-Z]/,
message: 'Must contain an uppercase letter'
},
{
validator: /[\d]/,
message: 'Must contain a digit'
},
]
2019-09-28 15:20:56 +00:00
})
return (
2019-09-28 18:14:02 +00:00
<form onSubmit={(e) => {
e.preventDefault()
if (isValid) console.log(form)
}}>
2019-09-28 15:20:56 +00:00
<h1>Errors & Validation</h1>
<input {...auto('username')} placeholder="Username" />
{errors.username && 'Must be longer than 3'}
2019-09-28 17:00:49 +00:00
<input {...auto('email')} placeholder="EMail" />
{errors.email}
2019-09-28 15:20:56 +00:00
<input {...auto('password')} placeholder="Password" type="password" />
2019-09-28 17:00:49 +00:00
{errors.password}
2019-09-28 15:20:56 +00:00
2019-09-28 18:14:02 +00:00
<input type="submit" />
2019-09-28 15:20:56 +00:00
</form>
)
}
ReactDOM.render(<Index />, document.getElementById('errors'))