Skip to content
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

feat: z.string.creditCard() - support Credit Card Validation #4037

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

ysknsid25
Copy link

@ysknsid25 ysknsid25 commented Mar 19, 2025

issue: #4039

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Added robust credit card validation to string input checks, ensuring proper formatting and verification with clear error feedback.
  • Tests
    • Integrated comprehensive tests verifying various valid and invalid credit card formats, ensuring reliable validation across multiple card types.
  • Documentation
    • Updated README files to include the new creditCard() method in the z.string() schema for credit card validation.

Copy link

coderabbitai bot commented Mar 19, 2025

Walkthrough

The changes integrate credit card validation into the string validation library. Updates extend the StringValidation type in both the deno and src modules by adding a new literal "creditCard". New methods and a validation function (using regex and the Luhn algorithm) are added to the string type to enable credit card checks. Corresponding tests have been introduced to verify both valid and invalid credit card numbers, and the validation chain now supports custom error messages.

Changes

File(s) Change Summary
deno/.../ZodError.ts, src/.../ZodError.ts Updated StringValidation type to include "creditCard", modifying object syntax (e.g., removing semicolon) to support the new validation.
deno/.../__tests__/string.test.ts, src/.../__tests__/string.test.ts Added tests for credit card validation, asserting that valid numbers pass and invalid ones produce an error ("Invalid credit card number").
deno/.../__tests__/validations.test.ts, src/.../__tests__/validations.test.ts Enhanced instantiation tests by appending creditCard() calls to z.string(), including variants with a custom error message.
deno/.../types.ts, src/.../types.ts Introduced a new check in ZodStringCheck for credit cards, added the isValidCreditCard function (using regex and the Luhn algorithm), and defined new methods creditCard() and the getter isCreditCard.
README.md, README_KO.md, README_ZH.md, deno/lib/README.md Added documentation for the new creditCard() method in the z.string() schema, explaining its purpose for credit card validation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Schema as z.string()
    participant Parser as _parse()
    participant Validator as isValidCreditCard()
    participant Tester as safeParse()

    User->>Schema: Chain .creditCard() / .creditCard({ message })
    Tester->>Schema: Validate input
    Schema->>Parser: Execute _parse(input)
    Parser->>Validator: Check credit card format
    Validator-->>Parser: Return true/false
    Parser-->>Tester: Return success/error details
Loading

Poem

I'm a hopping rabbit, quick and keen,
Adding credit card checks to keep our code clean.
Valid numbers march, while fakes take flight,
With regex and Luhn, everything's just right.
My bunny heart leaps with glee each day—
Thump-thump, our validations lead the way!


🪧 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 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 Mar 19, 2025

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit b457e55
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/67dc1648e206b30008c3bad7
😎 Deploy Preview https://deploy-preview-4037--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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
deno/lib/__tests__/validations.test.ts (1)

143-158: 💡 Verification agent

🧩 Analysis chain

Verify implementation of credit card validation logic.

The PR mentions using the Luhn algorithm and regex for validation, but the implementation details aren't visible in these files. Ensure the actual validation logic is implemented in the corresponding type files and is thoroughly tested with both valid and invalid credit card numbers.


🏁 Script executed:

#!/bin/bash
# Check for the implementation of creditCard validation logic
echo "Searching for creditCard implementation in types files:"
rg -A 10 "creditCard\s*\(" --glob "**/*types*.ts"

echo "Searching for Luhn algorithm implementation:"
rg -A 10 "luhn|isValidCreditCard" --glob "**/*.ts"

echo "Checking for credit card validation tests:"
rg "test.*creditCard" --glob "**/*test*.ts"

Length of output: 4373


Action Required: Enhance Credit Card Validation Testing

The credit card validation logic has been correctly implemented in the type files (evident in both deno/lib/types.ts and src/types.ts, where the creditCard method and the Luhn algorithm via isValidCreditCard are present). However, dedicated tests verifying the correctness of this logic—particularly tests for both valid and invalid credit card inputs—are missing from the test suite.

  • Location of Implementation:

    • deno/lib/types.ts and src/types.ts include the creditCard method and the Luhn algorithm logic.
  • Testing Coverage:

    • The existing test file (deno/lib/__tests__/validations.test.ts) instantiates the credit card validation but does not provide explicit test cases that validate the behavior for valid versus invalid card numbers.

Please add comprehensive tests targeting the credit card validation, covering edge cases with both correctly formatted (and valid per Luhn) credit card numbers and deliberately invalid inputs.

🧹 Nitpick comments (2)
src/__tests__/string.test.ts (1)

932-996: Comprehensive test coverage for credit card validation!

Your test suite for credit card validation is thorough and well-structured. It includes:

  • Various card types (American Express, Diners Club, Discover, JCB, MasterCard, UnionPay, Visa)
  • Different formats (with spaces, with dashes)
  • Numerous error cases (invalid numbers, wrong length, letters, mixed dividers, invalid providers, etc.)

The test assertion pattern is consistent with other validation tests in the file.

Consider using Jest's test.each for more concise parameterized testing in the future:

test.each([
  ["378282246310005", "American Express"],
  ["371449635398431", "American Express"],
  // ...other valid cards
])('should validate %s (%s)', (cardNumber, cardType) => {
  expect(creditCard.safeParse(cardNumber).success).toEqual(true);
});
src/types.ts (1)

694-726: Consider adding JSDoc comments to improve documentation

It would be helpful to add JSDoc comments explaining the purpose and behavior of the credit card validation, particularly noting which card providers are supported and any limitations.

/**
 * Validates a credit card number using format checks and the Luhn algorithm.
 * Supports major providers: Visa, Mastercard, American Express, Discover, JCB, UnionPay, and Diners Club.
 * Accepts numbers with or without spaces/hyphens as separators.
 * @param cardNumber The credit card number to validate
 * @returns boolean indicating if the card number is valid
 */
function isValidCreditCard(cardNumber: string): boolean {

Also applies to: 810-839

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f204123 and 39af1e6.

📒 Files selected for processing (8)
  • deno/lib/ZodError.ts (1 hunks)
  • deno/lib/__tests__/string.test.ts (2 hunks)
  • deno/lib/__tests__/validations.test.ts (1 hunks)
  • deno/lib/types.ts (6 hunks)
  • src/ZodError.ts (1 hunks)
  • src/__tests__/string.test.ts (2 hunks)
  • src/__tests__/validations.test.ts (1 hunks)
  • src/types.ts (6 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
deno/lib/types.ts (4)
deno/lib/helpers/parseUtil.ts (1) (1)
  • addIssueToContext (72-89)
src/helpers/parseUtil.ts (1) (1)
  • addIssueToContext (72-89)
deno/lib/ZodError.ts (2) (2)
  • ZodIssueCode (18-35)
  • ZodIssueCode (37-37)
src/ZodError.ts (2) (2)
  • ZodIssueCode (18-35)
  • ZodIssueCode (37-37)
src/types.ts (2)
src/helpers/parseUtil.ts (1) (1)
  • addIssueToContext (72-89)
src/ZodError.ts (2) (2)
  • ZodIssueCode (18-35)
  • ZodIssueCode (37-37)
🔇 Additional comments (21)
src/__tests__/validations.test.ts (2)

149-149: LGTM: creditCard() validation method properly added.

The addition of z.string().creditCard() follows the same pattern as other string validation methods like email() and url(), maintaining API consistency.


156-156: LGTM: Custom error message parameter implemented correctly.

The implementation allows for custom error messages following the same pattern as other validation methods.

deno/lib/ZodError.ts (1)

112-113: LGTM: String validation type properly extended.

The StringValidation type has been correctly extended to include "creditCard" as a valid option, ensuring proper error handling for credit card validation.

src/ZodError.ts (1)

112-113: LGTM: String validation type properly extended in sync with Deno version.

The StringValidation type has been correctly extended to include "creditCard" as a valid option, maintaining consistency between the Node.js and Deno versions of the library.

deno/lib/__tests__/validations.test.ts (2)

150-150: LGTM: creditCard() validation method added consistently.

The addition of the creditCard validation method follows the same pattern as in the Node.js version.


157-157: LGTM: Custom error message parameter implemented consistently.

The custom error message implementation is consistent with the Node.js version and other validation methods.

src/__tests__/string.test.ts (1)

547-557: Well-implemented property checks for the new credit card validator!

The getter tests follow the existing pattern and correctly verify that isCreditCard is set to true while ensuring all other validation properties remain false. This maintains consistency with the other string validators.

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

548-558: Well implemented property validation checks

These assertions correctly establish that a string with credit card validation maintains the expected type check state, consistent with other validation types in the codebase.


933-997: Comprehensive credit card validation tests

The test suite for credit card validation is very thorough, covering:

  • Various card providers (American Express, Diners Club, Discover, JCB, MasterCard, UnionPay, Visa)
  • Formatted numbers with spaces and dashes
  • Diverse error cases including invalid checksums, wrong formats, and illegal characters
  • Custom error message verification

The validation tests handle common real-world scenarios like spaces and dashes in card numbers, which users often include when entering their information.

src/types.ts (6)

629-629: Clean type extension for credit card validation

The addition of a "creditCard" kind to the ZodStringCheck type is well-structured and consistent with other validation types.


694-726: Well-structured regex patterns for credit card validation

The implementation includes comprehensive regex patterns for different card providers (Visa, Mastercard, Amex, etc.) which will ensure robust validation. The approach of having separate regexes for general format, sanitization, and provider-specific validation is thorough.


810-839: Solid implementation of credit card validation with Luhn algorithm

The isValidCreditCard function is well-implemented with:

  1. Proper sanitization of input
  2. Format validation using regex
  3. Provider-specific pattern matching
  4. Luhn algorithm validation for checksum verification

This multi-layered approach ensures robust credit card validation beyond simple format checks.


1143-1153: Proper integration into the parsing logic

The credit card validation is correctly integrated into the _parse method, following the same pattern as other string validations.


1377-1382: Clean implementation of the creditCard method

The creditCard() method follows the same pattern as other validation methods, allowing for optional custom error messages.


1440-1442: Consistent getter implementation

The isCreditCard getter follows the same pattern as other validation getters, maintaining consistency throughout the codebase.

deno/lib/types.ts (6)

628-629: Addition of creditCard validation type looks good!

The new string validation type for credit cards is properly integrated into the existing ZodStringCheck type union.


691-725: Well-structured regex patterns for credit card validation.

The regex patterns are comprehensive and handle different credit card formats:

  • Main pattern validates both separated and non-separated formats
  • Sanitize regex properly handles removing spaces and hyphens
  • Provider-specific patterns accurately cover major card issuers

The commenting style and organization also fit well with the codebase.


810-839: Solid implementation of the Luhn algorithm for credit card validation.

The implementation:

  1. Correctly sanitizes card numbers
  2. Follows an optimized version of the Luhn algorithm using a lookup table for the digit operations
  3. Verifies against known provider patterns before running the more expensive Luhn check
  4. Properly handles various card number formats

This is a clean and efficient approach to credit card validation.


1143-1153: Clean integration with the _parse method.

The credit card validation check is correctly integrated into the string parsing logic, following the same pattern as other validation types. The code properly:

  1. Checks if validation passes
  2. Gets context and adds appropriate issue data when validation fails
  3. Marks status as dirty on validation failure

This maintains consistency with existing validation implementations.


1377-1382: The creditCard method is well implemented.

This method follows the established pattern for adding validators to the string type. It correctly:

  1. Uses _addCheck to add the validation
  2. Handles optional error messages
  3. Returns a new ZodString instance with the check applied

This is consistent with other validation methods in the class.


1440-1442: The isCreditCard getter matches the library's pattern.

The getter method follows the established pattern for checking if specific validations are applied to a string instance. This consistency makes the API intuitive for users who are already familiar with Zod.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
README_ZH.md (1)

478-479: New Credit Card Validation Documentation

The addition of z.string().creditCard(); extends the string validation methods as intended. To improve user clarity, please consider adding a brief note (or an inline comment) that explains the method’s behavior—such as mentioning that it validates numbers via the Luhn algorithm and supports custom error messages—similar to how other validations are documented.

deno/lib/README.md (1)

833-833: New Credit Card Validation Method Documentation

The addition of the z.string().creditCard(); line clearly documents the new credit card validation feature in the string validation list. This aligns with the PR objective of introducing credit card checks (based on the Luhn algorithm as noted in the PR description).

It would be beneficial to include a brief inline note or a link to the relevant Luhn algorithm reference so that users immediately understand this method’s purpose and implementation details—especially since similar methods in this section often include hint text (e.g., for .email(), .url(), etc.).

README.md (1)

833-833: Announce New Credit Card Validation Method

The new creditCard() method added to the string validations is clearly visible at line 833. Consider adding a brief inline comment or accompanying documentation that explains what validation rules are applied (e.g. based on regex and the Luhn algorithm) and what error message users can expect upon failure. This extra context could be very helpful for users adopting this new feature.

README_KO.md (1)

783-783: Documentation Update: Credit Card Validation Addition

The new z.string().creditCard() method is now listed alongside the other string validation methods. It’s clear and consistent with the rest of the examples. To improve clarity for users, consider adding a brief note (or a comment in the docs) that mentions this method uses the Luhn algorithm for validating credit card numbers and supports custom error messages. This additional context could help users immediately understand the underlying mechanism and usage options.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 39af1e6 and b457e55.

📒 Files selected for processing (4)
  • README.md (1 hunks)
  • README_KO.md (1 hunks)
  • README_ZH.md (1 hunks)
  • deno/lib/README.md (1 hunks)

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