All files / src/helpers validationUtils.js

100% Statements 68/68
100% Branches 43/43
100% Functions 11/11
100% Lines 62/62

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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220                                30x 30x 30x 42x   41x         2x   39x 5x 5x     34x 15x 13x 13x     2x 1x 1x     20x   30x   30x           2x 1x     1x   1x           113x     113x   6x     6x   3x       4x   4x 4x                       113x         113x 30x     104x 104x   42x                   5x 5x 8x 8x   10x   9x 9x                 3x 3x                                               103x 103x 103x 206x   104x               102x 2x         100x 5x 5x                   60x                             103x 103x   103x 99x     103x              
/* eslint-disable no-param-reassign */
import is from 'is_js';
import {FieldStatus, throwError} from "./helpers";
import handlerMatcher, {
  RuleWhichNeedsArray,
  RuleWhichNeedsBoolean
} from "../ruleHandlers/matchers";
import {createNewFieldState} from './initializationUtils';
 
/**
 * If all fields in the state has their status !== error
 * Then we will set the isFormOK to true then return the state.
 * Just mutate the value since it's already a new state object
 *
 */
export function checkIsFormOK(schema, componentState) {
  const properties = Object.keys(schema);
  let isError = false;
  properties.some(prop => {
    if (prop === 'collectValues') return false;
 
    if (
      is.propertyDefined(schema[prop], 'isRequired') &&
      schema[prop].isRequired === false &&
      componentState[prop].status !== FieldStatus.error
    )
      return false;
 
    if (componentState[prop].status === FieldStatus.error) {
      isError = true;
      return true;
    }
 
    if (componentState[prop].status === FieldStatus.normal) {
      if (is.not.propertyDefined(schema[prop], 'default')) {
        isError = true;
        return true;
      }
 
      if (schema[prop].default !== componentState[prop].value) {
        isError = true;
        return true;
      }
    }
    return false;
  });
  componentState.isFormOK = !isError;
 
  return componentState;
}
 
 
 
function handleBeforeValidation(fieldValue, handler) {
  if (is.function(handler)) {
    return handler(fieldValue);
  }
  /* eslint no-console: 0 */
  console.warn(`[Veasy]: Expect beforeValidation to be a function \
while the value is ${handler}`);
  return fieldValue;
}
 
 
 
function extractUserDefinedMsg(handlerName, schema) {
  const result = { schema, userErrorText: '' };
 
  // No user message, just return
  if (is.not.array(schema[handlerName])) return result;
 
  const currentSchema = schema[handlerName];
 
  // Handle the case where the value of rule is array
  if (RuleWhichNeedsArray.includes(handlerName)) {
    // No user message, just return
    if (is.not.array(currentSchema[0])) return result;
  }
 
  // The most common case: [0] is rule and [1] is errText
  result.schema = { [handlerName]: currentSchema[0] };
  // eslint-disable-next-line prefer-destructuring
  result.userErrorText = currentSchema[1];
  return result;
}
 
 
 
function ruleRunner(
  ruleName,
  ruleHandler,
  fieldName,
  value,
  pschema
) {
  const { schema, userErrorText } = extractUserDefinedMsg(
    ruleName,
    pschema
  );
 
  if (RuleWhichNeedsBoolean.includes(ruleName)) {
    if (schema[ruleName] === false) return;
  }
 
  const result = ruleHandler(fieldName, value, schema);
  if (result.isValid) return;
 
  throwError(value, userErrorText || result.errorText);
}
 
 
 
function handleReliesOn(
  fieldReliesOnSchema,
  fieldState,
  allState
) {
  const originalFieldState = {...fieldState};
  Object.keys(fieldReliesOnSchema).forEach(reliedField => {
    const reliesKeySchema = fieldReliesOnSchema[reliedField];
    Object.keys(reliesKeySchema).forEach(rule => {
 
      if (is.not.propertyDefined(handlerMatcher, rule)) return;
 
      try {
        ruleRunner(
          rule,
          handlerMatcher[rule],
          reliedField,
          allState[reliedField].value, // Here we need to swap the field value to the target value
          reliesKeySchema
        );
      } catch (err) {
        // Restore the original value
        err.value = originalFieldState.value;
        throw err;
      }
    });
  });
}
 
 
 
/**
 * It will run through the user's settings for a field,
 * and try matching to the matchers.js,
 * if according rule could be found,
 * it will then execute the according rule function.
 * For instance:
 * if user sets a `minLength` for a field,
 * This function will invoke the minLength()
 *
 */
function runMatchers(
  matcher,
  fieldState,
  fieldSchema,
  allState
) {
  const fieldName = Object.keys(fieldSchema)[0];
  const schema = fieldSchema[fieldName];
  Object.keys(schema).forEach(ruleInSchema => {
    if (is.propertyDefined(matcher, ruleInSchema)) {
      // eslint-disable-next-line no-use-before-define
      ruleRunner(
        ruleInSchema,
        matcher[ruleInSchema],
        fieldName,
        fieldState.value,
        schema
      );
    }
    else if (ruleInSchema === 'beforeValidation') {
      fieldState.value = handleBeforeValidation(
        fieldState.value,
        schema.beforeValidation
      );
    }
    else if (ruleInSchema === 'reliesOn') {
      const fieldReliesOnSchema = fieldSchema[fieldName].reliesOn;
      handleReliesOn(
        fieldReliesOnSchema,
        fieldState,
        allState
      )
    }
    // TODO: Do something when the rule is not match
    // else if (ruleInSchema !== 'default') {
    // }
  });
  return fieldState;
}
 
 
 
/**
 * This is the main entry for all validator.
 * It will generate the initial state to start with
 *
 */
export function rulesRunner(
  value,
  schema,
  allState
) {
  const fieldState = createNewFieldState();
  fieldState.value = value;
 
  if (is.existy(value) && is.not.empty(value)) {
    fieldState.status = FieldStatus.ok;
  }
 
  return runMatchers(
    handlerMatcher,
    fieldState,
    schema,
    allState
  );
}