All files / src/helpers validationUtils.js

97.83% Statements 90/92
93.06% Branches 67/72
100% Functions 15/15
98.82% Lines 84/85

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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327                                            35x 35x 35x 47x   46x         2x   44x 6x 6x     38x 19x 17x 17x     2x 1x 1x     20x   35x   35x                 1x 1x                     121x     121x   6x     6x   3x       4x 4x 4x 4x                       121x         121x 30x     112x 112x   46x                   14x       13x   1x       1x           14x                 6x 6x 9x 9x   11x   10x           10x 10x                 4x 4x                         4x 4x   4x 4x   4x           4x 4x               2x   2x                                             108x 108x   108x       4x 4x 4x             4x 2x 2x         105x         1x           105x 211x 6x 6x 6x               205x   107x                         61x                               108x 108x   108x 104x     108x                
// @flow
/* eslint-disable no-param-reassign,array-callback-return,consistent-return, max-len */
import is from 'is_js';
import type {ComponentState, FieldSchema, FieldState, HandlerFunc, Schema, Matcher, FieldRules, BeforeValidationHandler, ReliesFieldRules} from "../flowTypes";
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: Schema,
  componentState: 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: mixed,
  handler: BeforeValidationHandler
) {
  Eif (is.function(handler)) {
    return handler(fieldValue);
  }
  return fieldValue;
}
 
 
 
function extractUserDefinedMsg(
  handlerName: string,
  schema: FieldRules
) {
  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
  const [rule, errText] = currentSchema;
  result.schema[handlerName] = rule;
  result.userErrorText = errText;
  return result;
}
 
 
 
function ruleRunner(
  ruleName: string,
  ruleHandler: HandlerFunc,
  fieldName: string,
  value: mixed,
  fieldRules: FieldRules
) {
  const { schema, userErrorText } = extractUserDefinedMsg(
    ruleName,
    fieldRules
  );
 
  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: Schema,
  allState: ComponentState,
  reliedFieldName: string
) {
  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: ReliesFieldRules,
  fieldState: FieldState,
  allSchema: Schema,
  allState: ComponentState
) {
  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;
      }
    });
  });
}
 
 
function handleOnlyWhen(
  fieldOnlyWhenSchema: ReliesFieldRules,
  fieldState: FieldState,
  allSchema: Schema,
  allState: ComponentState
): boolean {
  return Object.keys(fieldOnlyWhenSchema).every(reliedFieldName => {
    const reliesKeySchema = fieldOnlyWhenSchema[reliedFieldName];
 
    return Object.keys(reliesKeySchema).every(rule => {
      Iif (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) {
        return false;
      }
      return true;
    });
  });
}
 
 
/**
 * 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: Matcher,
  fieldState: FieldState,
  fieldSchema: FieldSchema,
  allSchema?: Schema,
  allState?: ComponentState
) {
  const fieldName = Object.keys(fieldSchema)[0];
  const fieldRules = fieldSchema[fieldName];
 
  if (
    'onlyWhen' in fieldRules &&
    is.not.empty(fieldRules.onlyWhen)
  ) {
    const fieldOnlyWhenOnSchema = fieldSchema[fieldName].onlyWhen;
    Eif (allSchema && allState && fieldOnlyWhenOnSchema) {
      const result = handleOnlyWhen(
        fieldOnlyWhenOnSchema,
        {...fieldState},
        allSchema,
        allState
      );
 
      if (result === false) {
        fieldState.status = FieldStatus.normal;
        return fieldState;
      }
    }
  }
 
  if (
    'beforeValidation' in fieldRules &&
    fieldRules.beforeValidation != null &&
    is.function(fieldRules.beforeValidation)
  ) {
    fieldState.value = handleBeforeValidation(
      fieldState.value,
      fieldRules.beforeValidation
    );
  }
 
  Object.keys(fieldRules).forEach(ruleInSchema => {
    if (ruleInSchema === 'reliesOn') {
      const fieldReliesOnSchema = fieldSchema[fieldName].reliesOn;
      Eif (allSchema && allState && fieldReliesOnSchema) {
        handleReliesOn(
          fieldReliesOnSchema,
          fieldState,
          allSchema,
          allState
        )
      }
    }
    else if (is.propertyDefined(matcher, ruleInSchema)) {
      // eslint-disable-next-line no-use-before-define
      ruleRunner(
        ruleInSchema,
        matcher[ruleInSchema],
        fieldName,
        fieldState.value,
        fieldRules
      );
    }
 
    // 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: mixed,
  fieldSchema: FieldSchema,
  allSchema?: Schema,
  allState?: ComponentState
) {
  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
  );
}