Last active
June 4, 2018 03:04
-
-
Save glendaviesnz/51472d4e028577d9e87efca9eaab7cd8 to your computer and use it in GitHub Desktop.
Add validation component to validated field
This file contains hidden or 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
// 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