pomodoro/client/components/Form.jsx
2016-11-10 16:48:56 +01:00

68 lines
1.2 KiB
JavaScript

import { h, Component } from 'preact';
// modules > lodas
import set from 'set-value';
import { forEach, bindAll } from 'lowline';
// import Input from '../components/Input.jsx'
export default class Form extends Component {
constructor(props) {
super(props);
bindAll(this, ['register', 'validate']);
this.inputs = {};
}
toJSON() {
const attrs = {};
// eslint-disable-next-line
for (let name in this.inputs) {
const input = this.inputs[name];
const value = input.getValue();
if (value) set(attrs, name, value);
}
return attrs;
}
validate() {
let errorCount = 0;
// eslint-disable-next-line
for (let name in this.inputs) {
const input = this.inputs[name];
if (!input.isValid()) {
if (errorCount === 0) {
input.focus();
}
errorCount += 1;
}
}
return !errorCount;
}
register(name) {
return (input) => {
if (input) {
input.validation = this.validation[input.props.name];
this.inputs[name] = input;
} else {
delete this.inputs[name];
}
};
}
reset() {
forEach(this.inputs, (input) => input.reset());
}
}