All files / src/helpers validationUtils.js

100% Statements 74/74
98.04% Branches 50/51
100% Functions 12/12
100% Lines 68/68

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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256                                  31x 31x 31x 43x   42x         2x   40x 6x 6x     34x 15x 13x 13x     2x 1x 1x     20x   31x   31x           2x 1x     1x   1x           115x     115x   6x     6x   3x       4x   4x 4x                       115x         115x 30x     106x 106x   43x                   10x       9x   1x       1x           10x                 6x 6x 9x 9x   11x   10x           10x 10x                 4x 4x                                                 104x 104x 104x 208x   105x               103x 2x         101x 6x 6x                     60x                               104x 104x   104x 100x     104x                
/* eslint-disable no-param-reassign */
import is from 'is_js';
import {getNestedValue} from "./collectValuesUtils";
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 grabValueForReliesField(
  allSchema,
  allState,
  reliedFieldName
) {
  let result;
 
  if (
    is.propertyDefined(allState, reliedFieldName) &&
    is.propertyDefined(allState[reliedFieldName], "value")
  ) {
    result = allState[reliedFieldName].value
  }
  else Eif (
    is.propertyDefined(allSchema, "collectValues") &&
    is.propertyDefined(allSchema.collectValues, reliedFieldName)
  ) {
    result = getNestedValue(
      allSchema.collectValues[reliedFieldName],
      allState
    )
  }
 
  return result;
}
 
function handleReliesOn(
  fieldReliesOnSchema,
  fieldState,
  allSchema,
  allState
) {
  const originalFieldState = {...fieldState};
  Object.keys(fieldReliesOnSchema).forEach(reliedFieldName => {
    const reliesKeySchema = fieldReliesOnSchema[reliedFieldName];
    Object.keys(reliesKeySchema).forEach(rule => {
 
      if (is.not.propertyDefined(handlerMatcher, rule)) return;
 
      const reliedFieldValue = grabValueForReliesField(
        allSchema,
        allState,
        reliedFieldName
      );
 
      try {
        ruleRunner(
          rule,
          handlerMatcher[rule],
          reliedFieldName,
          reliedFieldValue, // 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,
  allSchema,
  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,
        allSchema,
        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,
  fieldSchema,
  allSchema,
  allState
) {
  const fieldState = createNewFieldState();
  fieldState.value = value;
 
  if (is.existy(value) && is.not.empty(value)) {
    fieldState.status = FieldStatus.ok;
  }
 
  return runMatchers(
    handlerMatcher,
    fieldState,
    fieldSchema,
    allSchema,
    allState
  );
}