Good Form implementation for React. Easy drop-in validation. Supports arrays and nested structures. Helps to reduce boilerplate without being opinionated on style. Typescript support.
npm install react-good-form
Good Form supports basic validations such as email, minLength, maxLength etc. out of the box. It automatically emits onChange events and provides values for fields. onSubmit callback is only triggered when submitting a valid form. Otherwise form will focus to first invalid field.
import { Form } from "react-good-form"
class EmailForm extends React.Component {
state = {
email: ""
}
render() {
return (
<Form
value={this.state}
onChange={person => {
this.setState(person)
}}
onSubmit={() => {
alert(this.state.email)
}}
>
{({ Input }, { invalid, touched }) => (
<div>
<h1>Log in</h1>
<div style={{ color: invalid("email") && touched("email") ? "red" : undefined }}>
<label>Email</label>
<Input email required for="email" />
</div>
<button>OK</button>
</div>
)}
</Form>
)
}
}You can create arbitary rules by providing a rule function.
const rule = email => email.endsWith("hotmail.com")
<Input
rule={rule}
email={true}
for="email"
/>Or an regular expression.
const regExp = /(123456|password)/
<Input
type="password"
regExp={regExp}
for="password"
/>Provide paths to nested structures as arrays.
<div style={{ color: invalid(["address", "street"]) && touched(["address", "street"]) && "red" }}>
<label>Street</label>
<Input for={["address", "street"]} minLength={5} maxLength={100} />
</div>