Profiles·Public

yup

semver>=0.32.0 <2.0.0postconditions9functions7last verified2026-06-23coverage score78%

Postconditions — what we check

  • validate · validate-rejects
    error
    Whendata fails validation against the schema
    ThrowsPromise rejection with ValidationError
    Required handlingCaller MUST wrap validate() in try-catch or use .catch() handler. Without error handling, validation failures cause unhandled promise rejections that crash the application or lead to silent failures. Use pattern: try { const value = await schema.validate(data); } catch (error) { /* handle */ }
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[1]
  • validateSync · validatesync-throws
    error
    Whendata fails validation against the schema
    ThrowsValidationError
    Required handlingCaller MUST wrap validateSync() in try-catch block. Without error handling, validation failures throw uncaught exceptions that crash the application. Invalid data will not be caught, leading to data corruption or security vulnerabilities. Use pattern: try { const value = schema.validateSync(data); } catch (error) { /* handle */ }
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • validateSync · validatesync-async-test-throws
    error
    WhenvalidateSync() is called on a schema that has one or more async test() functions (i.e., test() functions that return a Promise). validateSync() cannot await async tests — when it encounters a Promise-returning test, it throws a plain Error immediately. This is a programmer error: schemas with async validators (e.g., async validators that check uniqueness in the database) must use validate() not validateSync().
    ThrowsError with message: "Validation test of type: \"<type>\" returned a Promise during a synchronous validate. This test will finish after the validate call has returned" This is a plain Error object, NOT a ValidationError — the schema itself is misconfigured for synchronous use. Confirmed from node_modules/yup/index.js line 386.
    Required handlingUse validate() (async) instead of validateSync() when the schema has any async test() rules. Common async test patterns in SaaS apps: - Checking uniqueness: schema.test('unique', 'Email taken', async (val) => !(await db.user.findByEmail(val))) - Checking resource existence: schema.test('exists', 'Not found', async (id) => !!(await db.find(id))) These MUST use validate() not validateSync(). Detection pattern: if you see this error in production, find which test() returns a Promise and replace validateSync() with await validate().
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[3]
  • validateAt · validateat-rejects
    error
    Whendata at the specified path fails validation
    ThrowsPromise rejection with ValidationError
    Required handlingCaller MUST wrap validateAt() in try-catch or use .catch() handler. Without error handling, validation failures cause unhandled promise rejections.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4]
  • validateSyncAt · validatesyncat-throws
    error
    Whendata at the specified path fails validation
    ThrowsValidationError
    Required handlingCaller MUST wrap validateSyncAt() in try-catch block. Without error handling, validation failures throw uncaught exceptions.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[5]
  • isValid · isvalid-non-validation-error-rethrows
    warning
    WhenisValid() is called without a catch handler, and a custom test() function in the schema throws a non-ValidationError exception. This occurs when: (a) An async test() makes a database/network call that rejects: schema.test('unique', 'taken', async (val) => !(await db.findByEmail(val))) — if db.findByEmail() throws a DatabaseError, isValid() propagates it. (b) An async test() throws an unexpected TypeError or other runtime error. (c) An async test() throws explicitly (e.g., throw new Error('service unavailable')) instead of returning false. Most developers use isValid() assuming it "always resolves" — it does NOT when non-ValidationError exceptions occur in test functions.
    ThrowsWhatever non-ValidationError the test() function throws. Common cases: - DatabaseError / Prisma errors (when test() checks uniqueness in DB) - NetworkError / FetchError (when test() calls an external API) - TypeError (when test() encounters unexpected input types) - Generic Error (when test() throws new Error(...)) Confirmed from index.js line 930: `throw err` — the error is not wrapped or transformed, it propagates as-is to the caller.
    Required handlingAlways wrap isValid() in try-catch when the schema contains any test() functions that could throw non-ValidationError exceptions: try { const valid = await schema.isValid(data); if (!valid) { // Validation failed (ValidationError was caught internally) return res.status(400).json({ error: 'Invalid data' }); } // data is valid } catch (error) { // Non-ValidationError from a test() function (DB error, network error, etc.) console.error('Validation service error:', error); return res.status(500).json({ error: 'Validation service unavailable' }); } If you want guaranteed no-throw behavior, use: const valid = await schema.isValid(data).catch(() => false); BUT: this silently treats all errors (including infrastructure outages) as validation failures — use with caution. Best practice: use validate() instead of isValid() in server-side code so validation errors are explicit and infrastructure errors are not swallowed.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[3]
  • cast · cast-type-error
    error
    Whencast() is called without a try-catch, assert is not set to false, and the input value cannot be coerced to the schema's expected type. This occurs when: (a) A string that is not a valid number is cast to number() schema: number().cast('not-a-number') → throws TypeError (NaN is not type 'number') (b) An object with missing required structure is cast to object() schema with strict transforms. (c) External API data with wrong types is cast to a strict schema. Note: number().cast('123') succeeds (returns 123). number().cast('abc') throws. date().cast('not-a-date') throws. object().cast('{"a":1}') may succeed via JSON.
    ThrowsTypeError with message: "The value of <path> could not be cast to a value that satisfies the schema type: \"<type>\". attempted value: <value>" This is a plain TypeError (not a ValidationError). It is thrown synchronously. Confirmed from node_modules/yup/index.js line 772. Note: cast() errors are TypeErrors, not ValidationErrors. Catch blocks that only handle yup.ValidationError will NOT catch cast errors.
    Required handlingWrap cast() in a try-catch when input may not be safely castable: try { const parsed = schema.cast(rawInput); return { success: true, value: parsed }; } catch (error) { if (error instanceof TypeError) { // Cast failed — input type is fundamentally incompatible with schema console.error('Type cast failed:', error.message); return { success: false, error: 'Invalid data type' }; } throw error; } Alternatively, use assert: false to return null/undefined on failure: const result = schema.cast(value, { assert: false }); if (result == null) { // Cast failed — handle gracefully } Or use validate() instead — it runs the cast AND reports why it failed via ValidationError with a user-readable message.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[3]
  • cast · cast-transform-throws
    warning
    Whencast() is called and a custom transform() function throws an uncaught error. While rare, custom transforms registered via schema.transform((value, original) => ...) can throw if they encounter unexpected input. This propagates synchronously from cast() without being converted to ValidationError. Also: ObjectSchema.cast() recursively casts nested fields — if any nested field's cast throws, it propagates up from the parent schema's cast().
    ThrowsWhatever the transform() function throws — typically TypeError or plain Error. Not a ValidationError. Propagates synchronously from the cast() call.
    Required handlingEnsure custom transform() functions handle all edge cases and do not throw. For defensive coding: try { const result = schema.cast(value); } catch (error) { // Handle both TypeError (type check failure) and custom transform errors console.error('Cast failed:', error.message); }
    costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[3]
  • ~standard.validate · standard-validate-infrastructure-error-rethrows
    warning
    Whenschema['~standard'].validate(value) is called without a catch handler (typically by integration libraries like react-hook-form's standardResolver, tRPC procedures, conform actions, or TanStack Form validators), and a custom test() function in the schema throws a non-ValidationError exception. Common cases: (a) An async test() makes a database query that rejects: schema.test('unique', 'taken', async (val) => !(await db.findByEmail(val))) — if db.findByEmail() throws, ~standard.validate() propagates the DatabaseError. (b) An async test() calls an external API that rejects (network failure, 5xx). (c) A test() throws unexpectedly (TypeError on bad input access). Standard Schema consumers commonly write code assuming ~standard.validate resolves either { value } or { issues } — they do NOT wrap it in try/catch because the spec implies validation failures are returned as data, not thrown. This assumption is correct for ValidationError but WRONG for infrastructure errors.
    ThrowsWhatever non-ValidationError the test() function throws. Common cases: - DatabaseError / Prisma errors (when test() checks uniqueness in DB) - NetworkError / FetchError (when test() calls an external API) - TypeError (when test() encounters unexpected input types) - Generic Error (when test() throws new Error('service unavailable')) Confirmed from index.js line 1206 (`throw err`) and line 2581 — the error is not wrapped or transformed, it propagates as-is on the returned Promise.
    Required handlingWhen using the Standard Schema interface directly (rare — usually wrapped by an integration), wrap the call in try-catch: try { const result = await schema['~standard'].validate(rawInput); if (result.issues) { // Validation failed — ValidationError converted to issues[] return { ok: false, errors: result.issues }; } return { ok: true, value: result.value }; } catch (error) { // Non-ValidationError from a test() function (DB error, network error, etc.) // Standard Schema consumers commonly do NOT handle this — infrastructure // failures appear as crashes / 500 errors with no validation context. console.error('Validation infrastructure error:', error); return { ok: false, errors: [{ message: 'Validation service unavailable' }] }; } When using yup via an integration library (react-hook-form standardResolver, tRPC, conform), check the integration's error model — most propagate the rejection as an unhandled promise. Ensure your schema's async test() functions internally try-catch any I/O and return false / a string message instead of throwing. Best practice for schemas with async test() that hit external systems: schema.test('unique', async (val) => { try { return !(await db.findByEmail(val)); } catch (error) { // ✅ Convert infrastructure errors to validation messages console.error('Uniqueness check failed:', error); return new yup.ValidationError('Could not verify email uniqueness', val); } });
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[6][3]

Sources

Every postcondition cites at least one of these. Numbered to match the footnotes above.

  1. [1]github.com/jquense/yuphttps://github.com/jquense/yup#schemavalidatevalue-options-promise
  2. [2]github.com/jquense/yuphttps://github.com/jquense/yup#schemavalidatesyncvalue-options-any
  3. [3]github.com/jquense/yuphttps://github.com/jquense/yup
  4. [4]github.com/jquense/yuphttps://github.com/jquense/yup#schemavalidateatpath-string-value-any-options-object-promise
  5. [5]github.com/jquense/yuphttps://github.com/jquense/yup#schemavalidatesyncat-path-string-value-any-options-object-any
  6. [6]github.com/standard-schema/standard-schemahttps://github.com/standard-schema/standard-schema
Need a different package?
Request a profile