Skip to content

Instantly share code, notes, and snippets.

@kuanee
Last active October 12, 2020 11:51
Show Gist options
  • Save kuanee/16a275992370e389b9cf0f12f5bd620c to your computer and use it in GitHub Desktop.
Save kuanee/16a275992370e389b9cf0f12f5bd620c to your computer and use it in GitHub Desktop.
Using Joi Validation with redux-form
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);
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;
};
}
@kaleem-elahi
Copy link

kaleem-elahi commented Oct 8, 2020

@kuanee I want to use Joi with Redux-form, Can you please explain how you did it ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment