yup#ValidationError TypeScript Examples

The following examples show how to use yup#ValidationError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: test-utils.tsx    From abacus with GNU General Public License v2.0 7 votes vote down vote up
/**
 * Validation Error Displayer
 */
export async function validationErrorDisplayer<T>(promise: Promise<T>): Promise<T> {
  try {
    return await promise
  } catch (err) {
    if (err instanceof ValidationError) {
      expect(err.errors).toEqual([])
    }
    throw err
  }
}
Example #2
Source File: handler.ts    From NLW-3.0 with MIT License 6 votes vote down vote up
errorHandler: ErrorRequestHandler = (error, request, response, next) => {
	if (error instanceof ValidationError) {
		let errors: ValidationErrors = {};

		error.inner.forEach(err => {
			errors[err.path] = err.errors;
		})

		return response.status(400).json({ message: 'Validation fails', errors });
	}

	console.error(error);

	return response.status(500).json({ message: 'Internal server error' });
}
Example #3
Source File: getValidationErrors.ts    From gobarber-mobile with MIT License 6 votes vote down vote up
export default function getValidationErrors(err: ValidationError): Errors {
  const validationErrors: Errors = {};

  err.inner.forEach(error => {
    validationErrors[error.path] = error.message;
  });

  return validationErrors;
}
Example #4
Source File: handler.ts    From happy with MIT License 6 votes vote down vote up
errorHandler: ErrorRequestHandler = (error, request, response, next) => {
  if (error instanceof ValidationError) {
    let errors: ValidationErrors = {};

    error.inner.forEach(err => {
      errors[err.path] = err.errors;
    })

    return response.status(400).json({ message: 'Validation fails', errors });
  }

  console.error(error);

  return response.status(500).json({ message: 'Internal Server Error' });
}
Example #5
Source File: getValidationErrors.ts    From front-entenda-direito with GNU General Public License v3.0 6 votes vote down vote up
export default function getValidationErrors(err: ValidationError): Errors {
  const validationErrors: Errors = {};

  err.inner.forEach((error) => {
    validationErrors[error.path] = error.message;
  });

  return validationErrors;
}
Example #6
Source File: handler.ts    From NextLevelWeek with MIT License 6 votes vote down vote up
errorHandler: ErrorRequestHandler = (error, req, res, next) => {
    if (error instanceof ValidationError) {
        let errors: ValidationErrors = {}

        error.inner.forEach(err => {
            errors[err.path] = err.errors;
        });

        return res.status(400).json({ message: 'Validation fails.', errors });
    }

    console.error(error);

    return res.status(500).json({ message: 'Internal server error.' });
}
Example #7
Source File: getValidationErrors.ts    From rocketredis with MIT License 6 votes vote down vote up
export default function getValidationErrors(err: ValidationError): Errors {
  const validationErrors: Errors = {}

  err.inner.forEach(error => {
    validationErrors[error.path] = error.message
  })

  return validationErrors
}
Example #8
Source File: validates.ts    From frontegg-react with MIT License 6 votes vote down vote up
validateSchemaSync = (props: any, values: any) =>
  new Promise((resolve) => {
    validateSchema(props)
      .validate(values, { abortEarly: false })
      .then(() => resolve({}))
      .catch((errors) => {
        resolve(
          errors.inner
            .map((error: ValidationError) => ({ [error.path]: error.message }))
            .reduce((p: object, n: object) => ({ ...p, ...n }), {})
        );
      });
  })
Example #9
Source File: getValidationErrors.ts    From gobarber-project with MIT License 6 votes vote down vote up
export default function getValidationErrors(err: ValidationError): Errors {
  const validationErrors: Errors = {};

  err.inner.forEach(error => {
    validationErrors[error.path] = error.message;
  });

  return validationErrors;
}
Example #10
Source File: ExpressErrorYup.ts    From expresso with MIT License 6 votes vote down vote up
async function ExpressErrorYup(
  err: any,
  req: Request,
  res: Response,
  next: NextFunction
): Promise<Response<any, Record<string, any>> | undefined> {
  if (err instanceof ValidationError) {
    const errType = `Yup Validation Error:`
    const message = err.errors.join('<br/>') || 'Yup Validation Error !'

    console.log(logErrServer(errType, message))

    const error = {
      code: 422,
      message,
      errors:
        err.inner.length > 0
          ? err.inner.reduce((acc: any, curVal: any) => {
              acc[`${curVal.path}`] = curVal.message || curVal.type
              return acc
            }, {})
          : { [`${err.path}`]: err.message || err.type },
    }
    return res.status(422).json(error)
  }

  next(err)
}
Example #11
Source File: handler.ts    From happy with MIT License 6 votes vote down vote up
errorHandler: ErrorRequestHandler = (error, req, res, next) => {

  if (error instanceof ValidationError) {
    let errors: ValidationErrors = {}

    error.inner.forEach(err => {
      errors[err.path] = err.errors;
    });

    return res.status(400).json({ message: "Validation fails", errors })
  }

  console.error(error);

  return res.status(500).json({ message: "Internal server error" });
}
Example #12
Source File: handler.ts    From nlw-03-omnistack with MIT License 6 votes vote down vote up
errorHandler: ErrorRequestHandler = (error, request, response, next) => {
  if (error instanceof ValidationError) {
    let errors: ValidationErrors = {};

    error.inner.forEach(err => {
      errors[err.path] = err.errors;
    });

    return response.status(400).json({ message: 'Validation fails.', errors });
  }

  console.error(error);

  return response.status(500).json({ message: 'Internal server error.' });
}
Example #13
Source File: getValidationErrors.ts    From gobarber-project with MIT License 5 votes vote down vote up
export default function getValidationErrors(err: ValidationError): Errors {
  const validationErrors: Errors = {};

  err.inner.forEach((error) => {
    validationErrors[error.path] = error.message;
  });
  return validationErrors;
}
Example #14
Source File: core.ts    From graphene with MIT License 5 votes vote down vote up
coreHandler: Middleware = async (req, res) => {
  if (req.body === "" || !Object.keys(req.body).length) {
    res
      .writeHead(400, { "Content-Type": "application/json" })
      .end(JSON.stringify({ msg: "Body can't be empty!" }));
    return;
  }

  try {
    const options = (await optionSchema.validate(req.body, {
      abortEarly: false
    })) as OptionSchema;
    const { image, format, length } = await generateImage(options);

    res
      .writeHead(200, {
        "Content-Type": `image/${format === "svg" ? "svg+xml" : format}`,
        "Content-Length": length
      })
      .end(image);
  } catch (err) {
    if (err instanceof ValidationError && err.name === "ValidationError") {
      res
        .writeHead(400, { "Content-Type": "application/json" })
        .end(JSON.stringify({ msg: err.errors }));
    }
    return;
  }

  /* c8 ignore start */
  await logger.info("Incoming POST request", {
    body: req.body || "",
    headers: {
      accept: req.headers.accept || "",
      "content-type": req.headers["content-type"] || "",
      origin: req.headers.origin || "",
      referer: req.headers.referer || "",
      "user-agent": req.headers["user-agent"] || ""
    },
    port: req.socket.remotePort || "",
    ipv: req.socket.remoteFamily || ""
  });
  /* c8 ignore end */
}
Example #15
Source File: option.ts    From cron-validate with MIT License 4 votes vote down vote up
validateOptions = (
  inputOptions: InputOptions
): Result<Options, string[]> => {
  try {
    // load default presets
    presets()

    let preset: OptionPreset
    if (inputOptions.preset) {
      if (typeof inputOptions.preset === 'string') {
        if (!optionPresets[inputOptions.preset]) {
          return err([`Option preset ${inputOptions.preset} does not exist.`])
        }

        preset = optionPresets[inputOptions.preset as string]
      } else {
        preset = inputOptions.preset
      }
    } else {
      preset = optionPresets.default
    }

    const unvalidatedConfig = {
      presetId: preset.presetId,
      preset,
      ...{
        useSeconds: preset.useSeconds,
        useYears: preset.useYears,
        useAliases: preset.useAliases ?? false,
        useBlankDay: preset.useBlankDay,
        allowOnlyOneBlankDayField: preset.allowOnlyOneBlankDayField,
        mustHaveBlankDayField: preset.mustHaveBlankDayField ?? false,
        useLastDayOfMonth: preset.useLastDayOfMonth ?? false,
        useLastDayOfWeek: preset.useLastDayOfWeek ?? false,
        useNearestWeekday: preset.useNearestWeekday ?? false,
        useNthWeekdayOfMonth: preset.useNthWeekdayOfMonth ?? false,
        seconds: {
          lowerLimit: preset.seconds.lowerLimit ?? preset.seconds.minValue,
          upperLimit: preset.seconds.upperLimit ?? preset.seconds.maxValue,
        },
        minutes: {
          lowerLimit: preset.minutes.lowerLimit ?? preset.minutes.minValue,
          upperLimit: preset.minutes.upperLimit ?? preset.minutes.maxValue,
        },
        hours: {
          lowerLimit: preset.hours.lowerLimit ?? preset.hours.minValue,
          upperLimit: preset.hours.upperLimit ?? preset.hours.maxValue,
        },
        daysOfMonth: {
          lowerLimit:
            preset.daysOfMonth.lowerLimit ?? preset.daysOfMonth.minValue,
          upperLimit:
            preset.daysOfMonth.upperLimit ?? preset.daysOfMonth.maxValue,
        },
        months: {
          lowerLimit: preset.months.lowerLimit ?? preset.months.minValue,
          upperLimit: preset.months.upperLimit ?? preset.months.maxValue,
        },
        daysOfWeek: {
          lowerLimit:
            preset.daysOfWeek.lowerLimit ?? preset.daysOfWeek.minValue,
          upperLimit:
            preset.daysOfWeek.upperLimit ?? preset.daysOfWeek.maxValue,
        },
        years: {
          lowerLimit: preset.years.lowerLimit ?? preset.years.minValue,
          upperLimit: preset.years.upperLimit ?? preset.years.maxValue,
        },
      },
      ...inputOptions.override,
    }

    const optionsSchema = yup
      .object({
        presetId: yup.string().required(),
        preset: optionPresetSchema.required(),
        useSeconds: yup.boolean().required(),
        useYears: yup.boolean().required(),
        useAliases: yup.boolean(),
        useBlankDay: yup.boolean().required(),
        allowOnlyOneBlankDayField: yup.boolean().required(),
        mustHaveBlankDayField: yup.boolean(),
        useLastDayOfMonth: yup.boolean(),
        useLastDayOfWeek: yup.boolean(),
        useNearestWeekday: yup.boolean(),
        useNthWeekdayOfMonth: yup.boolean(),
        seconds: yup
          .object({
            lowerLimit: yup
              .number()
              .min(preset.seconds.minValue)
              .max(preset.seconds.maxValue),
            upperLimit: yup
              .number()
              .min(preset.seconds.minValue)
              .max(preset.seconds.maxValue),
          })
          .required(),
        minutes: yup
          .object({
            lowerLimit: yup
              .number()
              .min(preset.minutes.minValue)
              .max(preset.minutes.maxValue),
            upperLimit: yup
              .number()
              .min(preset.minutes.minValue)
              .max(preset.minutes.maxValue),
          })
          .required(),
        hours: yup
          .object({
            lowerLimit: yup
              .number()
              .min(preset.hours.minValue)
              .max(preset.hours.maxValue),
            upperLimit: yup
              .number()
              .min(preset.hours.minValue)
              .max(preset.hours.maxValue),
          })
          .required(),
        daysOfMonth: yup
          .object({
            lowerLimit: yup
              .number()
              .min(preset.daysOfMonth.minValue)
              .max(preset.daysOfMonth.maxValue),
            upperLimit: yup
              .number()
              .min(preset.daysOfMonth.minValue)
              .max(preset.daysOfMonth.maxValue),
          })
          .required(),
        months: yup
          .object({
            lowerLimit: yup
              .number()
              .min(preset.months.minValue)
              .max(preset.months.maxValue),
            upperLimit: yup
              .number()
              .min(preset.months.minValue)
              .max(preset.months.maxValue),
          })
          .required(),
        daysOfWeek: yup
          .object({
            lowerLimit: yup
              .number()
              .min(preset.daysOfWeek.minValue)
              .max(preset.daysOfWeek.maxValue),
            upperLimit: yup
              .number()
              .min(preset.daysOfWeek.minValue)
              .max(preset.daysOfWeek.maxValue),
          })
          .required(),
        years: yup
          .object({
            lowerLimit: yup
              .number()
              .min(preset.years.minValue)
              .max(preset.years.maxValue),
            upperLimit: yup
              .number()
              .min(preset.years.minValue)
              .max(preset.years.maxValue),
          })
          .required(),
      })
      .required()

    const validatedConfig: Options = optionsSchema.validateSync(
      unvalidatedConfig,
      {
        strict: false,
        abortEarly: false,
        stripUnknown: true,
        recursive: true,
      }
    )

    return valid(validatedConfig)
  } catch (validationError) {
    return err((validationError as ValidationError).errors)
  }
}