Skip to content
Snippets Groups Projects
form.js 2.01 KiB
Newer Older
clemo's avatar
clemo committed
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
clemo's avatar
clemo committed
      // convert
clemo's avatar
clemo committed
      if ("function" === typeof this.validation[element].convert) {
        this.validation[element].checkValue =
            this.validation[element].convert(this.validation[element].value);
      } else if ("string" === typeof this.validation[element.convert]) {
        this.validation[element].value =
            validator[this.validation[element].convert](object[element]);
      } else {
        this.validation[element].checkValue = this.validation[element].value;
      }
clemo's avatar
clemo committed
      // validate
      if ("string" === this.validation[element].validator &&
          "function" === typeof validator[this.validation[element].validator] &&
          "string" === typeof this.validation[element].checkValue) {
        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) {
        return this.validation[element].validator(
            this.validation[element].checkValue);
      } else if ("undefined" === typeof this.validation[element].validator) {
        return true; // no validation, so valid
clemo's avatar
clemo committed
      } else {
clemo's avatar
clemo committed
        return false;
clemo's avatar
clemo committed
      }
clemo's avatar
clemo committed
    } else { // check everything
      for (let e in this.validation) {
        if (!this.isValid(e)) {
          return false;
        }
      }
      return true;
    }
  } // end isValid
}

exports.default = Form;