form-rules
Common form groups, for React forms with validation messages:
Feedback appears when you leave a field, or submit the form. While internally MobX powers the display of messages, you're free to store your data as usual. No hooks, weird syntax or higher-order components required.
Usage
Import validation styles, and create a component:
import { Form, FormGroupUtil, FormNumber } from "form-rules";
class YourForm extends React.Component {
constructor() {
super();
this.form = new FormGroupUtil();
this.state = {
age: 18
};
this.translationService = {
translate(english = "Value too small.") {
return english; // Or translate however you like.
}
};
}
render() {
return (
<Form form={this.form} onSubmit={() => console.log(this.state)}>
<FormNumber
form={this.form}
label="How old are you?"
max={200}
min={18}
name="age"
onChange={ev => this.setState({ [ev.target.name]: ev.target.value })}
required={true}
translationService={this.translationService}
value={this.state.age}
/>
<button>Submit</button>
</Form>
);
}
}
Build your own
Write form rules in "just" React. FormGroupUtil understands that you have added or removed an error, whenever a FormError instance mounts or unmounts.
class YourFormGroup extends React.Component {
constructor() {
super();
this.group = this.props.form.group();
}
render() {
return (
<FormGroup group={this.group}>
{/** ...your label and input... */}
<FormErrors>
{this.props.value.length > maxLength && (
<FormError group={this.group}>Something is wrong.</FormError>
)}
</FormErrors>
</FormGroup>
)
}
}
License
MIT