Newer
Older
import debug from 'debug';
import validator from 'validator';
const log = debug('helper:form');
export class Form {
constructor(validation) { this.validation = validation; }
fill(object, check = true) {
for (let element in this.validation) {
this.validation[element].value = object[element];
if (check) {
this.validation[element].error = !this.isValid(element);
}
}
return this.validation;
} // end fill
isValid(element) {
if ("undefined" !== typeof element) { // check 1 element
if ("function" === typeof this.validation[element].convert) { // convert
this.validation[element].checkValue =
this.validation[element].convert(this.validation[element].value);
log("convert", element, this.validation[element].value, 'to',
this.validation[element].checkValue);
log("convert", element, this.validation[element].value, 'to',
this.validation[element].checkValue);
this.validation[element].checkValue =
validator[this.validation[element].convert](object[element]);
} else {
this.validation[element].checkValue = this.validation[element].value;
}
log(typeof this.validation[element].validator,
typeof validator[this.validation[element].validator],
typeof this.validation[element].checkValue);
if ("string" === typeof this.validation[element].validator &&
"function" === typeof validator[this.validation[element].validator] &&
"string" ===
typeof this.validation[element]
.checkValue) { // validation function
log("validat by validator string", element);
return validator[this.validation[element].validator](
this.validation[element].checkValue,
this.validation[element].options);
} else if ("function" === typeof this.validation[element].validator &&
"string" ===
typeof this.validation[element]
.checkValue) { // own validation function
return this.validation[element].validator(
this.validation[element].checkValue);
} else if (this.validation[element].required &&
("undefined" === typeof this.validation[element].checkValue ||
"" ===
this.validation[element]
.checkValue)) { // validation but no value
log("validat required but no value", element);
return false;
} else if ("undefined" === typeof this.validation[element].validator ||
!this.validation[element]
.required) { // no validation or not required
log("validat no validator (true)", element);