Created
January 24, 2018 04:36
-
-
Save dalcib/d65257e07f9ef2c166ea86cd14c7c147 to your computer and use it in GitHub Desktop.
AJV validator to use with react-final-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 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; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.