Skip to content

Fix: Accept object or string for date string validation error message #4067

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

DavidSemke
Copy link

@DavidSemke DavidSemke commented Apr 3, 2025

Overview

This PR corrects an inconsistency present in date string validation. Currently, in the documentation there is this example code in the Strings section:

z.string().date({ message: "Invalid date string!" });

However, this does not work as the string().date function currently only accepts a string argument for a custom error message (unlike all other ZodString functions). My changes allow a string or a string within an object as an argument.

Benefits

  1. Non-breaking (still accepts string argument, now also accepts object argument).
  2. Makes the date function of ZodString consistent with other ZodString functions.
  3. Fixes inconsistency with docs.

Result

import { z } from "./src";

const badDate = "not a date";
const customMsg = "I am custom";

// Custom error message as string
const strResult = z.string().date(customMsg).safeParse(badDate);
console.log(strResult.error?.issues[0].message) // prints "I am custom"

// Custom error message as string within object
const objResult = z.string().date({ message: customMsg }).safeParse(badDate);
console.log(objResult.error?.issues[0].message) // prints "I am custom"

Summary by CodeRabbit

  • New Features
    • Enhanced the date validation for user inputs by enabling customizable error messages. Invalid date entries now trigger more informative and context-specific feedback, whether a simple text message or structured error details are provided. This improvement helps users more easily identify and correct issues with date formats.

Copy link
Contributor

coderabbitai bot commented Apr 3, 2025

Walkthrough

This pull request introduces additional test cases and updates associated with the date validation functionality. Two new tests have been added (in both the Deno and src test files) to verify that custom error messages—whether provided as a string or as an object—are correctly applied when an invalid date string is supplied. In addition, the date method in the ZodString class (in both the Deno and src type files) has been updated to accept an errorUtil.ErrMessage and to process error messages using errorUtil.errToObj.

Changes

Files Change Summary
deno/lib/__tests__/string.test.ts
src/__tests__/string.test.ts
Added test cases for the date validation that verify custom error messages are returned correctly when an invalid date string is provided.
deno/lib/types.ts
src/types.ts
Updated the ZodString.date method signature to accept an optional errorUtil.ErrMessage instead of a string, and modified the implementation to use errorUtil.errToObj for error handling.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client Code
    participant Z as ZodString.date Method
    participant E as errorUtil.errToObj
    participant A as _addCheck

    C->>Z: Invoke date(customErrorMessage)
    Z->>E: Convert customErrorMessage to error object
    E-->>Z: Return error object
    Z->>A: Add validation check with error object
    A-->>Z: Validation check added
Loading

Possibly related issues

Poem

I’m a little rabbit, hopping with delight,
Testing each date, ensuring messages are right.
With code that now converts errors into witty tales,
I bounce through checks, leaving no validation fails.
Code changes in harmonies make my heart take flight!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 91dcd30 and 638bf3b.

📒 Files selected for processing (4)
  • deno/lib/__tests__/string.test.ts (1 hunks)
  • deno/lib/types.ts (1 hunks)
  • src/__tests__/string.test.ts (1 hunks)
  • src/types.ts (1 hunks)
🔇 Additional comments (4)
src/__tests__/string.test.ts (1)

663-678: Excellent implementation of custom error message tests for the date validator.

The added tests clearly verify that the date() validator can accept both a string and an object with a message property for custom error messages, which aligns with the PR's objective to make the API consistent with other string validators in Zod.

Both test cases properly verify that:

  1. The validation fails for an invalid date string
  2. The custom error message is correctly included in the error issues
src/types.ts (1)

1183-1184: Great improvement to API consistency!

This change allows the date method to accept either a string or an object for error messages, aligning it with the behavior of other ZodString validation methods. The update enhances usability while maintaining backward compatibility.

deno/lib/types.ts (1)

1183-1184: Consistent error message handling for date validation.

This change improves API consistency by aligning the date string validation error message parameter handling with other validation methods. The method now accepts either a string or an object for the error message, using errorUtil.errToObj() to properly process the input.

deno/lib/__tests__/string.test.ts (1)

664-679: LGTM: Good test coverage for the new error message functionality.

The added tests thoroughly verify both approaches for providing custom error messages to the date validator:

  1. Passing a string directly: z.string().date(customMsg)
  2. Passing an object with a message property: z.string().date({ message: customMsg })

Both tests correctly verify that the custom message appears in the error output when validation fails. The implementation aligns perfectly with the PR objectives of allowing string().date to accept either a string or an object argument, consistent with other ZodString functions.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Apr 3, 2025

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 638bf3b
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/67ee66040ef9ac00080e1641
😎 Deploy Preview https://deploy-preview-4067--guileless-rolypoly-866f8a.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

vercel bot commented Apr 3, 2025

Deployment failed with the following error:

Creating the Deployment Timed Out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant