Created
August 23, 2017 16:27
-
-
Save schuster-rainer/fac47dc737e72cef131f2e1f5ba57323 to your computer and use it in GitHub Desktop.
redux-form-immutable validator with JSON API
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 React from 'react'; | |
import { FormattedMessage } from 'react-intl'; | |
import { Field, reduxForm } from 'redux-form/immutable'; | |
import muiThemeable from 'material-ui/styles/muiThemeable'; | |
import './form'; | |
import validatejs from 'validate.js'; | |
const ExampleForm = ({onSubmit, ...props}) => ( | |
<form onSubmit={onSubmit}> | |
<Field | |
component={TextField} | |
floatingLabelText={<FormattedMessage id="NAME" />} | |
name="attributes.name" | |
/> | |
</form> | |
); | |
const validate = (values, props) => { | |
const message = <FormattedMessage id="VALIDATION_NAME_REQUIRED" />; | |
const constraints = { | |
'attributes.identifier': { | |
presence: { | |
message, | |
}, | |
}, | |
} | |
//TODO: immutable validator | |
const errors = validatejs(values.toJS(), constraints, {format: 'groupedNested'}); | |
return errors; | |
}; | |
export default reduxForm({ | |
enableReinitialize: true, | |
validate, | |
form: 'ExampleForm', | |
})(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
import validatejs from 'validate.js'; | |
import { fromJS } from 'immutable'; | |
validatejs.formatters.groupedNested = (errors) => | |
errors.reduce((acc, error) => { | |
const selector = error.attribute.split('.'); | |
return acc.updateIn(selector, fromJS([]), (l) => l.push(error.error)); | |
}, fromJS({})).toJS(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment