Skip to content

Instantly share code, notes, and snippets.

@schuster-rainer
Created August 23, 2017 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schuster-rainer/fac47dc737e72cef131f2e1f5ba57323 to your computer and use it in GitHub Desktop.
Save schuster-rainer/fac47dc737e72cef131f2e1f5ba57323 to your computer and use it in GitHub Desktop.
redux-form-immutable validator with JSON API
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);
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