1.0.13 • Published 5 years ago
simple-hoc-validator v1.0.13
simple-hoc-validator
Simple rule-based validation HOC
This is a very simple HOC, for someone who wants to do simple validations on React components. If you need advanced stuff, this is not it :) This was not made with performance in mind either, so...
Install
Install with npm:
$ npm install --save simple-hoc-validator
Usage
import React from 'react';
import withValidation from 'simple-hoc-validator';
const rules = [
{
field: 'name',
condition: value => value !== null && value !== undefined && value !== '',
error: 'Name is empty'
}, {
field: 'password',
condition: (value, obj) => value === obj.compare_password,
error: "Passwords don't match"
}
];
class MyFormComponent extends React.Component {
onSubmit() {
if (this.props.isValid(this.state)) {
submit();
}
}
render() {
const errors = this.props.validate(this.state);
if (errors.name) {
showNameError();
}
if (errors.password) {
showPasswordError();
}
}
}
export default withValidation(rules)(MyFormComponent);
Tests
Nah. Just works.
Licence
See LICENCE.
Contributing
As I use this for my own projects, I know this might not be the perfect approach for all the projects out there. If you have any ideas, just open an issue and tell me what you think.
If you'd like to contribute, please fork the repository and make changes as you'd like. Pull requests are warmly welcome.
MIT © Heber Nobre