Instruction
So we have a form:
render() {
return (
<form>
<Field
label="Title"
name="title"
component={this.renderField}
/>
<Field
label="Categories"
name="categories"
component={this.renderField}
/>
<Field
label="Post Content"
name="content"
component={this.renderField}
/>
</form>
);
}
And special function, which reders fields of form:
renderField(field) {
return (
<div className="form-group">
<label>{field.label}</label>
<input
className="form-control"
type="text"
{...field.input}
/>
</div>
);
};
Also, we have a special validation function:
function validate(values) {
const errors = {};
// Validation
if (!values.title || values.title.length < 3) {
errors.title = "Enter a title, that is at least 3 characters!!";
}
if (!values.categories) {
errors.categories = 'Enter some categories';
}
if (!values.content) {
errors.content = 'Enter some content please';
}
//IF errors is empty, the form is fine to submit
//IF errors has *any* properties, redux form assumes form is invalid
return errors;
}
Now we should add an error call to the function, which renders fields:
renderField(field) {
return (
<div className="form-group">
<label>{field.label}</label>
<input
className="form-control"
type="text"
{...field.input}
/>
{field.meta.error}
</div>
);
};
Then we should add submit button to the form:
<form>
<Field
label="Title"
name="title"
component={this.renderField}
/>
<Field
label="Categories"
name="categories"
component={this.renderField}
/>
<Field
label="Post Content"
name="content"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
Right now, the fields validated constantly:
Now we should add onSubmit to the render:
render() {
const {handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
label="Title"
name="title"
component={this.renderField}
/>
<Field
label="Categories"
name="categories"
component={this.renderField}
/>
<Field
label="Post Content"
name="content"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
);
}
And let's just view submit values to the console:
onSubmit(values) {
console.log(values);
}
Now let's handle the error messages. Let's make them disappear before we touch a field:
renderField(field) {
return (
<div className="form-group">
<label>{field.label}</label>
<input
className="form-control"
type="text"
{...field.input}
/>
{field.meta.touched ? field.meta.error : ''}
</div>
);
};
Some styling:
renderField(field) {
const { meta: {touched, error} } = field;
const className = `form-group ${touched && error ? 'has-danger' : ''}`;
return (
<div className={className}>
<label>{field.label}</label>
<input
className="form-control"
type="text"
{...field.input}
/>
<div className="text-help">
{touched ? error : ''}
</div>
</div>
);
};