-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
base: main
Are you sure you want to change the base?
feat: z.string.creditCard() - support Credit Card Validation #4037
Conversation
Signed-off-by: ysknsid25 <[email protected]>
WalkthroughThe changes integrate credit card validation into the string validation library. Updates extend the Changes
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
Poem
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for guileless-rolypoly-866f8a ready!Built without sensitive environment variables
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this 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
andsrc/types.ts
, where thecreditCard
method and the Luhn algorithm viaisValidCreditCard
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
andsrc/types.ts
include thecreditCard
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 documentationIt 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
📒 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 checksThese 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 testsThe 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 validationThe 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 validationThe 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 algorithmThe
isValidCreditCard
function is well-implemented with:
- Proper sanitization of input
- Format validation using regex
- Provider-specific pattern matching
- 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 logicThe 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 methodThe
creditCard()
method follows the same pattern as other validation methods, allowing for optional custom error messages.
1440-1442
: Consistent getter implementationThe
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:
- Correctly sanitizes card numbers
- Follows an optimized version of the Luhn algorithm using a lookup table for the digit operations
- Verifies against known provider patterns before running the more expensive Luhn check
- 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:
- Checks if validation passes
- Gets context and adds appropriate issue data when validation fails
- 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:
- Uses _addCheck to add the validation
- Handles optional error messages
- 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.
update README Signed-off-by: ysknsid25 <[email protected]>
There was a problem hiding this 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 DocumentationThe 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 DocumentationThe 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 MethodThe 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 AdditionThe 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
📒 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)
issue: #4039
Summary by CodeRabbit
Summary by CodeRabbit
creditCard()
method in thez.string()
schema for credit card validation.