Skip to content

Instantly share code, notes, and snippets.

@glendaviesnz
Last active June 4, 2018 03:04
Add validation component to validated field
// where the form is declared a simple string is used to indicated validation type
<input name="firstName" validation="required" />
// an object map is used in the form library to map this string name to a validation method and message
export const validationTypes = {
required: { validate: validateRequired, message: 'Field is required' },
email: { validate: validateEmail, message: 'Valid email address required' }
}
// a functional component is used to display validation errors
const ValidationError = ({ invalid, message }) => {
return (
<div>
{invalid &&
<span>{message}</span>
}
</div>
);
}
// within the form library any fields with the validation prop are replaced with a new div
// that wraps the field and the validation component. An invalidFields object is added the
// field component state to dictate if validation errors should be shown for individual fields
addValidationToField(field) {
let validation = field.props.validation;
return React.createElement('div', null,
field,
React.createElement(ValidationError, {
invalid: this.state.invalidFields[field.props.name],
message: this.validationTypes[validation].message
}, null));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment