javascript
Apply required field validation on redux form fields
You can simply create a required validation function and pass it to validate attributes of redux form fields to apply the required field validation on that field.
import React from 'react'
import { Field, reduxForm } from 'redux-form'
const requiredValidator = value => value ? undefined : 'Required'
const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} placeholder={label} type={type}/>
{touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
</div>
</div>
)
const FieldLevelValidationForm = (props) => {
const { handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit}>
<Field name="firstname" type="text"
component={renderField} label="First Name"
validate={[ requiredValidator ]}
/>
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Reset</button>
</div>
</form>
)
}
export default reduxForm({
form: 'fieldLevelValidation' // a unique identifier for this form
})(FieldLevelValidationForm)
Was this helpful?
Similar Posts