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"classEmailFormextendsReact.Component{state={email: ""}render(){return(<Formvalue={this.state}onChange={person=>{this.setState(person)}}onSubmit={()=>{alert(this.state.email)}}>{({ Input },{ invalid, touched })=>(<div><h1>Log in</h1><divstyle={{color: invalid("email")&&touched("email") ? "red" : undefined}}><label>Email</label><Inputemailrequiredfor="email"/></div><button>OK</button></div>)}</Form>)}}You can create arbitary rules by providing a rule function.
construle=email=>email.endsWith("hotmail.com")<Inputrule={rule}email={true}for="email"/>Or an regular expression.
constregExp=/(123456|password)/<Inputtype="password"regExp={regExp}for="password"/>Provide paths to nested structures as arrays.
<divstyle={{color: invalid(["address","street"])&&touched(["address","street"])&&"red"}}><label>Street</label><Inputfor={["address","street"]}minLength={5}maxLength={100}/></div>