Easy form validation
Inspired by react-reformed
- Installation
- Demo
- Usage
- HOC
- Inline Form
- Advanced
- Custom validation rules
- Custom error messages
- API
- Component options
npm install @bynder/react-formulation --save
If you want to try out a little demo first, you can check it out here or try it yourself:
git clone [email protected]:Bynder/react-formulation.git
cd react-formulation
npm install
npm start
React formulation offers two types of forms. The first one is a high order component for larger forms, the second one is a component for a form with just one input field and a submit and cancel button.
If you have a larger form you'll use the High order component:
import { withValidation, Validator } from '@bynder/react-formulation';
@withValidation({
validateOn: 'change', // optional, default value is 'blur'
schema: {
firstname: {
required: true,
},
lastname: {
minLength: 2,
maxLength: 30,
},
// ...more validation rules
}
})
class YourForm extends React.Component {
componentWillMount() {
this.props.setInitialModel({
firstname: 'Foo',
lastname: 'Bar',
});
}
onSubmit() {
// handle submit
}
render() {
// Wrap your entire form in a <Validator.Form> component
// Add a submit handler
// Wrap every input in a <Validator> component
// Provide a name to Validator (must match the name you provided in the schema)
return (
<Validator.Form onSubmit={this.onSubmit}>
<Validator name="firstname">
<input />
</Validator>
<Validator name="lastname">
<input />
</Validator>
<button type="submit">Submit</submit>
</Validator.Form>
);
}
}
export default YourForm;
For forms with just a single input you'll use the Inline Form component
import { InlineForm } from '@bynder/react-formulation';
// Wrap your input and buttons in an <InlineForm> component.
// Provide the name of your input, validation rules, initial value,
// and optionally custom messages to this component.
// Add an onSubmit handler.
// Wrap the input in a <InlineForm.Field> component.
const YourInlineForm = () => (
<InlineForm
name="firstname"
initialValue="Foo"
rules={{
required: true,
minLength: 2,
maxLength: 30,
}}
messages={{
// Custom validation messages
required: 'Please don\'t leave me empty',
minLength: condition => `Please use a minimum of ${condition} characters`,
}}
onSubmit={(val) => { // handle submit }}
>
<InlineForm.Field resetOnEscape>
<label htmlFor="inlineform-name">Name</label>
<input id="inlineform-name" />
</InlineForm.Field>
<InlineForm.Errors /> // (optional) This will display the error messages
<InlineForm.Cancel> // (optional) This will reset your form when you click cancel
<button type="button">
Cancel
</button>
</InlineForm.Cancel>
<InlineForm.Submit> // (optional) This disables the submit button if the field isn't valid
<button type="submit">
Save
</button>
</InlineForm.Submit>
);
export default YourInlineForm;
The basic usage might not be enough for you. Luckily we added some advanced options.
Of course you can add your own validation rules to the schema. Here you can see an example of how that might work:
@withValidation({
schema: {
name: {
required: true, // default validation
mustNotContainSpecialCharacters: { // custom validation
test: val => !(/[^a-zA-Z0-9]/).test(val),
message: 'This field cannot contain special characters',
},
},
// ...
}
})
// ...
In the example above you can see that it's possible to add custom validation rules and custom messages for those rules. You can also add custom messages for the default validation rules. You can use this option to add translations.
@withValidation({
schema: {
name: {
required: true,
},
// ...
},
messages: {
required: 'This field is required.',
}
})
// ...
The following options are injected by the react-formulation
high order component.
Allows you to set the initial values of the model
Usage:
this.props.setInitialModel({
firstname: 'Foo',
lastname: 'Bar',
});
Returns true
if any of the fields have been changed, otherwise returns false
.
Usage:
this.props.isTouched;
Returns the errors for the given input (name).
Usage:
this.props.getSchema('lastname');
Returns:
// console.log(this.props.getSchema('lastname'));
{
errors: [{
condition: true,
rule: 'required'
}],
isTouched: true,
isValid: false,
}
Returns the complete error schema.
Usage:
<button disabled={!this.props.schema.isValid && !this.props.isTouched} />
Returns:
// console.log(this.props.schema);
{
isValid: true,
fields: {
firstname: {
errors: [],
isTouched: true,
isValid: true
},
lastname: {
errors: [{
condition: true,
rule: 'required'
}],
isTouched: true,
isValid: false,
}
}
}
Validates the entire form.
Usage:
this.props.validateForm();
Set a specific property on a model.
Usage:
this.props.setProperty('firstname', 'foo');
Override the existing model
Usage:
this.props.setModel({
firstname: 'bar',
lastname: 'foo',
});
Tells you if your submit button should be disabled.
Usage:
<button type="submit" disabled={this.props.isButtonDisabled} />
Removes the validation errors from your form, sets isValid
to null.
Usage:
this.props.resetValidation();
Returns:
// console.log(this.props.schema);
{
isValid: null,
fields: {
firstname: {
errors: [],
isTouched: false,
isValid: null
},
// ...
}
}
Removes all values from all models.
Usage:
this.props.clearForm();
Resets the validation and sets the form to its initial model.
Usage:
this.props.resetForm();
Sets the forms touched state to true
.
Usage:
this.props.setTouched();
Sets the forms touched state to false
.
Usage:
this.props.setUntouched();
Returns the complete model.
Usage:
this.props.model;
Returns
{
firstname: {
isTouched: false,
value: 'Foo'
},
lastname: {
isTouched: true,
value: 'Bar'
},
phone: {
isTouched: false,
value: '0123456789'
}
}
Property | Type | Default | Description |
---|---|---|---|
name | string | undefined | Name of the model |
hideErrors | bool | false | Hide error messages |
Property | Type | Default | Description |
---|---|---|---|
onSubmit | func | undefined | Submit handler |
... props |
Property | Type | Default | Description |
---|---|---|---|
name | string | undefined | Name of the model |
initialValue | object | undefined | Initial value of the model |
onSubmit | func | undefined | Submit handler |
rules | object | undefined | Validation rules |
messages | object | undefined | Custom validation messages |
... props |
Property | Type | Default | Description |
---|---|---|---|
resetOnEscape | bool | false | Resets the input value on escape |
... props |
Property | Type | Default | Description |
---|---|---|---|
... props |
Property | Type | Default | Description |
---|---|---|---|
style | object | { display: 'inline' } |
CSS style attribute |
... props |
Property | Type | Default | Description |
---|---|---|---|
style | object | { display: 'inline' } |
CSS style attribute |
... props |