import React, { Component } from 'react'; import Formous from 'formous'; class ErrorText extends Component { render() { return
{this.props.errorText}
} } class MyComponent extends Component { componentWillReceiveProps(nextProps) { // Set default form values (might be appropriate in a different method this.props.setDefaultValues({ age: 33, name: 'Sir Fluffalot', }); } handleSubmit(formStatus, fields) { // 4 -> handle Formouse arguments passed to handler if (!formStatus.touched) { alert('Please fill out the form.'); return; } if (!formStatus.valid) { alert('Please address the errors in the form.'); return; } // All good! Do something with fields.name.value and fields.age.value console.log(formStatus, fields); } render() { const { fields: { age, name }, formSubmit, // 2 -> Export Formous validation function to current scope } = this.props; return
// 3 -> wrap form event handler with Formous vailidation function
} } const fields = { name: { tests: [ { critical: true, failProps: { errorText: 'Name is required.', }, test(value) { return value !== ''; }, } ], }, age: { tests: [ { critical: true, failProps: { errorText: 'Age should be a number.', }, test(value) { return /^\d*$/.test(value); }, }, { critical: false, failProps: { errorText: 'Are you sure you\'re that old? :o', }, test(value) { return +value < 120; }, }, ], }, }; export default Formous(fields)(MyComponent) // 1 - wrap target component