Skip to content

Instantly share code, notes, and snippets.

@dalcib
Created January 24, 2018 04:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dalcib/d65257e07f9ef2c166ea86cd14c7c147 to your computer and use it in GitHub Desktop.
Save dalcib/d65257e07f9ef2c166ea86cd14c7c147 to your computer and use it in GitHub Desktop.
AJV validator to use with react-final-form
import Ajv from 'ajv/dist/ajv.min';
import AddIf from 'ajv-keywords/keywords/if';
const makeValidator = (schema) => {
const ajv = new Ajv({ allErrors: true, coerceTypes: true });
// Add If-then-else from ajv-keywords package
AddIf(ajv);
// Add custom keyword
ajv.addKeyword('customKeyword', {
validate: (aSchema, value) => customValidationFunction(value),
errors: false,
});
const validator = ajv.compile(schema);
// Return a redux-form compatible validation function
return (values) => {
const errors = {};
if (values.toJS) {
validator(values.toJS());
if (validator.errors) {
validator.errors.forEach((obj) => {
// Massage ajv errors to the { 'fieldName': 'errorMessage' } format expected by redux-form
if (obj.keyword === 'required') {
errors[obj.params.missingProperty] = obj.message;
} else {
errors[obj.dataPath.replace('.', '')] = obj.message;
}
});
}
}
return errors;
};
}
@JaneJeon
Copy link

JaneJeon commented Apr 7, 2021

This REALLY helped with integrating into the clusterfck bullsht that is react-admin, which uses react-final-form under the hood. You're a goddamn saint.

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