Skip to content

Instantly share code, notes, and snippets.

@strobox
Created July 5, 2016 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strobox/146e8839dc25c623db1d6afe80197cd7 to your computer and use it in GitHub Desktop.
Save strobox/146e8839dc25c623db1d6afe80197cd7 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import Formous from 'formous';
class ErrorText extends Component {
render() {
return <div style={{ color: '#f00' }}>
{this.props.errorText}
</div>
}
}
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 <div>
<form onSubmit={formSubmit(this.handleSubmit)}> // 3 -> wrap form event handler with Formous vailidation function
<div>
<input
placeholder="Name"
type="text"
value={name.value}
{ ...name.events }
/>
<ErrorText { ...name.failProps } />
</div>
<div>
<input
placeholder="Age"
type="text"
value={age.value}
{ ...age.events }
/>
<ErrorText { ...age.failProps } />
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
}
}
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment