Instruction
First of all let's add function where we are going to validate Fields, and declare it in reduxForm:
function validate() {
}
export default reduxForm({
validate,
form: 'PostsNewForm'
})(PostsNew);
Also, we should add a variable as parameter to this function, which will contain all values, which are passed to forms:
function validate(values) {
}
Now we should add a variable, which will contain errors:
function validate(values) {
const errors = {};
// Validation
//IF errors is empty, the form is fine to submit
//IF errors has *any* properties, redux form assumes form is invalid
return errors;
}
Finally, validation function could look like this:
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;
}
Final Code
import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form'
class PostsNew extends Component {
renderField(field) {
return (
<div className="form-group">
<label>{field.label}</label>
<input
className="form-control"
type="text"
{...field.input}
/>
</div>
);
};
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>
);
}
}
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;
}
export default reduxForm({
validate,
form: 'PostsNewForm'
})(PostsNew);