# All files / lib/form validator.tsx

100% Statements 12/12
100% Branches 8/8
100% Functions 4/4
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29

    1x
    8x
    8x
    8x

    6x

    6x

    2x

    2x

    2x

    8x

    1ximport {FormValue} from "./index";
    import {FormField} from "./index";
    import {FormErrors} from "./index";

    const validator = (fields: Array<FormField>, values: FormValue): FormErrors => {
      const fieldsWithRules = fields.filter(f => f.rules);
      const errors:FormErrors = {};
      fieldsWithRules.map((f:FormField) => {
        if (!errors[f.key]) {
          errors[f.key] = [];
        }

        f.rules && f.rules.map(rule => {
          if (rule.required && (!values[f.key])) {
            errors[f.key].push(rule.message);
          }
          if (rule.minLength && rule.minLength > values[f.key].length) {
            errors[f.key].push(rule.message);
          }
          if (rule.maxLength && rule.maxLength < values[f.key].length) {
            errors[f.key].push(rule.message);
          }
        });
      });

      return errors;
    };

    export default validator;