Last active
October 12, 2020 11:51
-
-
Save kuanee/16a275992370e389b9cf0f12f5bd620c to your computer and use it in GitHub Desktop.
Using Joi Validation with redux-form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import createValidator from 'joi_redux_form.js'; | |
import { reduxForm } from 'redux-form'; | |
const schema = { | |
name: Joi.string().required(), | |
description: Joi.string().required(), | |
}; | |
function ExampleForm(props) { | |
return ( | |
<form> | |
... | |
</form> | |
); | |
} | |
const ExampleReduxForm = reduxForm({ | |
form: 'example_form', | |
validate: createValidator(schema) | |
})(ExampleForm); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Joi = require('joi'); | |
// take a joi schema and create a validator function for redux form | |
export default function createValidator(schema) { | |
return values => { | |
const result = Joi.validate(values, schema, { abortEarly: false }); | |
if (result.error === null) { | |
return {}; | |
} | |
const errors = result.error.details.reduce((all, cur) => { | |
const allErrors = Object.assign({}, all); | |
const path = cur.path[cur.path.length - 1]; | |
const message = cur.message; | |
if (Object.prototype.hasOwnProperty.call(allErrors, path)) { | |
allErrors[path] += message; | |
} else { | |
allErrors[path] = message; | |
} | |
return allErrors; | |
}, {}); | |
return errors; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@kuanee I want to use Joi with Redux-form, Can you please explain how you did it ?