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: Add MAC Address validation (#3970) #3972

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

Conversation

sumit6499
Copy link

@sumit6499 sumit6499 commented Feb 6, 2025

This PR adds support for validating MAC addresses in Zod, addressing issue #3970. The validation ensures that input values conform to standard MAC address formats.

Changes Introduced:

  • Added a new MAC address validation method in the schema.
  • Supports both colon-separated (XX:XX:XX:XX:XX:XX) and dash-separated (XX-XX-XX-XX-XX-XX) formats.
  • Implemented unit tests to verify correct validation behavior.
  • Updated documentation with usage examples.

Testing Done:

  • Ran yarn test to ensure all existing and new tests pass.
  • Validated various correct and incorrect MAC address formats.

Checklist:

  • Added unit tests.
  • Verified no breaking changes.
  • Updated documentation.

Issue Reference:

Closes #3970.

Summary by CodeRabbit

  • New Features

    • Introduced MAC address validation that ensures proper formatting and consistent separators, highlighting support for standard 48-bit MAC addresses.
  • Documentation

    • Updated documentation with a dedicated section on MAC address validation, including examples of valid and invalid formats and clarifications for IP ranges.
  • Tests

    • Added tests to verify accurate MAC address parsing, ensuring that the new validations work reliably without affecting existing string validations.

Copy link

netlify bot commented Feb 6, 2025

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

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

@colinhacks
Copy link
Owner

@coderabbitai review this

Copy link

coderabbitai bot commented Feb 14, 2025

🧩 Analysis chain

@colinhacks I'll review the changes for the MAC address validation feature.


🏁 Script executed:

#!/bin/bash
# Fetch the PR diff
gh pr diff 3972

Length of output: 10746


@colinhacks Thank you for the PR. I've reviewed the changes for MAC address validation. The implementation looks solid with good test coverage. Here are a few suggestions for improvement:

  1. The MAC address regex could be more readable with comments explaining the pattern components. Consider:
// Matches 6 groups of 2 hexadecimal characters
// Each group is separated by either all colons or all dashes
const macRegex = /^
  (?:
    ([0-9A-Fa-f]{2}(:)){5}[0-9A-Fa-f]{2} | // colon-separated
    ([0-9A-Fa-f]{2}(-)){5}[0-9A-Fa-f]{2}   // dash-separated
  )$/x;
  1. Consider adding the case-insensitive flag (i) to the regex since MAC addresses are valid in both upper and lower case:
const macRegex = /^([0-9A-Fa-f]{2}(:)){5}[0-9A-Fa-f]{2}$|^([0-9A-Fa-f]{2}(-)){5}[0-9A-Fa-f]{2}$/i;
  1. There's a typo in the comment "seperators" → "separators"

  2. Optional enhancement: Consider adding an option to validate specifically for unicast/multicast MAC addresses, as some use cases might require this distinction.

The implementation is good to go, but these changes would make it even better. Let me know if you'd like me to explain any of these suggestions in more detail.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented Feb 14, 2025

Walkthrough

This pull request extends the string validation library with MAC address validation. Documentation in the README is updated with a new section explaining MAC validation and clarifies IP ranges with a "(CIDR)" note. The ZodString class is enhanced by adding a mac() method and integrating a MAC check via a new isValidMac function. The StringValidation type now includes a "mac" option, and new tests have been added to verify the correct behavior of MAC validation compared to existing string validations.

Changes

File(s) Change Summary
README.md Added a new section for MAC address validation with examples; updated IP range section to include "(CIDR)" for clarity.
src/zod.ts, src/types.ts Added the mac() method in the ZodString class; implemented MAC address check using isValidMac function; updated the ip() method signature.
src/ZodError.ts Extended the StringValidation type to include "mac" as a valid option for MAC address validation.
src/__tests__/string.test.ts Introduced a new test suite for MAC address validation; added tests for valid/invalid MAC addresses and ensured isMac property is correctly set.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant Z as ZodString
    participant V as isValidMac
    U->>Z: Call mac() with input string
    Z->>V: Validate input using regex
    V-->>Z: Return true/false
    alt Valid MAC input
        Z-->>U: Return success result
    else Invalid MAC input
        Z-->>U: Return error message with issue details
    end
Loading

Poem

I'm a bunny in the code, full of cheer,
Hoppin' to validate with a MAC so dear.
Regex checks and tests in a playful spree,
CIDR, MAC, and IP dancing merrily.
With every hop, bugs flee—oh, coding glee!


🪧 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. (Beta)
  • @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

@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)
src/__tests__/string.test.ts (1)

1-976: ⚠️ Potential issue

Run Prettier to fix code style issues.

The test pipeline indicates code style issues. Please run Prettier on the test file to ensure consistent formatting.

🧰 Tools
🪛 GitHub Actions: test

[warning] 1-1: Code style issues found. Forgot to run Prettier?

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

942-976: Consider enhancing the MAC validation test suite.

While the test cases are comprehensive, consider these improvements:

  1. Add case-insensitive validation tests
  2. Add comments explaining the test cases
  3. Include additional edge cases:
    • Mixed case (e.g., "00:1a:2B:3c:4D:5e")
    • Leading/trailing whitespace
    • Invalid separators (e.g., "00/1A/2B/3C/4D/5E")

Here's a suggested enhancement:

 test("MAC validation", () => {
   const mac = z.string().mac();
+  // Basic validation
   expect(mac.safeParse("00:1A:2B:3C:4D:5E").success).toBe(true);
   expect(() => mac.parse("00:1A-2B:3C:4D:5E")).toThrow();

+  // Test cases for valid MAC addresses
   const validMacs = [
+    // Standard uppercase format with colons
     "00:1A:2B:3C:4D:5E",
     "FF:FF:FF:FF:FF:FF",
+    // Standard uppercase format with hyphens
     "01-23-45-67-89-AB",
+    // Mixed case format
+    "00:1a:2B:3c:4D:5e",
+    // Lowercase format
     "0a:1b:2c:3d:4e:5f",
+    // With whitespace (if supported)
+    " 00:1A:2B:3C:4D:5E ",
     // ... rest of the valid cases
   ];

+  // Test cases for invalid MAC addresses
   const invalidMacs = [
+    // Mixed separators
     "00:1A-2B:3C-4D:5E",
+    // No separators
     "001A2B3C4D5E",
+    // Too short
     "00:1A:2B:3C:4D",
+    // Too long
     "00:1A:2B:3C:4D:5E:FF",
+    // Invalid characters
     "00:1A:2B:3C:4D:GZ",
+    // Invalid separators
+    "00/1A/2B/3C/4D/5E",
     // ... rest of the invalid cases
   ];

   const macSchema = z.string().mac();
   expect(validMacs.every((mac) => macSchema.safeParse(mac).success)).toBe(true);
   expect(invalidMacs.every((mac) => macSchema.safeParse(mac).success)).toBe(false);
 });
src/types.ts (2)

699-702: Improve MAC address regex readability and case-insensitivity.

The MAC address regex pattern could be improved in the following ways:

  1. Add comments to explain the components
  2. Add case-insensitive flag
  3. Fix typo in comment ("seperators" → "separators")

Apply this diff to improve the regex pattern:

-// no support for mac without seperators
-// enforces all seperators should be either ':' or '-'
-const macRegex=/^([0-9A-Fa-f]{2}(:)){5}[0-9A-Fa-f]{2}$|^([0-9A-Fa-f]{2}(-)){5}[0-9A-Fa-f]{2}$/;
+// No support for MAC addresses without separators
+// Enforces all separators must be either ':' or '-'
+const macRegex = /^([0-9A-Fa-f]{2}(:)){5}[0-9A-Fa-f]{2}$|^([0-9A-Fa-f]{2}(-)){5}[0-9A-Fa-f]{2}$/i;
+// Explanation:
+// ^                     Start of string
+// [0-9A-Fa-f]{2}       Two hex digits
+// (:)                   Colon separator (captured)
+// {5}                   Repeat 5 times
+// [0-9A-Fa-f]{2}       Final two hex digits
+// $                     End of string
+// |                     OR
+// Same pattern but with hyphen separators

779-785: Simplify the MAC address validation function.

The validation function can be simplified by directly returning the test result.

Apply this diff to simplify the function:

-function isValidMac(mac:string) {
-  if (macRegex.test(mac)){
-    return true;
-  }
-
-  return false;
-}
+function isValidMac(mac: string): boolean {
+  return macRegex.test(mac);
+}
README.md (2)

813-813: MAC Address Validation Example Added
The example z.string().mac(); // Validate 48-bit MAC clearly illustrates the basic usage of the new MAC address validation method. Consider adding a brief note mentioning that the validator supports both colon-separated and dash-separated formats and that it applies case-insensitive matching to accommodate lower- and uppercase letters.


977-988: Detailed MAC Addresses Section
The new "MAC addresses" section provides clear examples of how to validate standard 48-bit MAC addresses. The examples include:

  • Valid cases with both colon ("00:1A:2B:3C:4D:5E") and dash ("98-76-54-32-10-FF") separations.
  • Invalid cases, including the case with an extra segment ("00:1A:2B:3C:4D:5E:FF") and a mixed separator format ("00:1A:2B-3C:4D:5E").

For improved clarity, consider including a comment (or a link to the implementation) explaining the underlying regex—for example, highlighting that the regex is designed to be case-insensitive and only allows one consistent separator throughout the string. Also, ensure that the heading starts at the beginning of the line as required by markdown lint rules.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

977-977: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e376cda and 97f55bf.

📒 Files selected for processing (4)
  • README.md (5 hunks)
  • src/ZodError.ts (1 hunks)
  • src/__tests__/string.test.ts (10 hunks)
  • src/types.ts (6 hunks)
🧰 Additional context used
🪛 GitHub Actions: test
src/__tests__/string.test.ts

[warning] 1-1: Code style issues found. Forgot to run Prettier?

README.md

[warning] 1-1: Code style issues found. Forgot to run Prettier?

🪛 markdownlint-cli2 (0.17.2)
README.md

977-977: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

🔇 Additional comments (8)
src/ZodError.ts (1)

110-110: LGTM!

The addition of "mac" to the StringValidation type is well-integrated with the existing validation types and follows the established pattern.

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

467-566: LGTM!

The isMac property checks are well-implemented and follow the established pattern for other string validation types. Each validation type correctly reports its isMac status.

src/types.ts (4)

628-629: LGTM!

The type definition for MAC address validation follows the established pattern for string validations.


1089-1099: LGTM!

The MAC address validation logic is well-integrated into the existing validation framework and follows the established pattern.


1178-1180: LGTM!

The mac() method is correctly implemented following the established pattern for string validation methods.


1384-1386: LGTM!

The isMac getter is correctly implemented following the established pattern for string validation getters.

README.md (2)

78-79: New Table of Contents Entry for MAC Addresses
The addition of the "MAC addresses" link in the table of contents ensures that the new validation feature is easily discoverable. This update is clear and consistent with the surrounding entries.


845-845: Custom Error Message for MAC Address Validation
The example z.string().mac({ message: "Invalid MAC address" }); shows how to override the default error message. This is a good practice for enhancing usability.

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 (1)
README.md (1)

1002-1002: Markdown Heading Alignment

The heading “### MAC addresses” on line 1002 appears to have leading whitespace. Please remove any extra spaces so that the heading starts at the beginning of the line in order to comply with markdownlint MD023.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

1002-1002: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 97f55bf and 79163a3.

📒 Files selected for processing (2)
  • README.md (5 hunks)
  • src/types.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/types.ts
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

1002-1002: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

🔇 Additional comments (2)
README.md (2)

78-79: TOC Update for MAC Addresses Feature

The addition of the new TOC item “MAC addresses” (along with "IP ranges (CIDR)") aligns well with the PR objectives. Please verify that the anchor "#mac-addresses" correctly links to the corresponding section below.


1006-1013: Comprehensive MAC Address Examples

The code snippet clearly demonstrates the usage of the new mac() validation method. It shows valid cases with both colon-separated and dash-separated MAC addresses as well as failure cases for improper formats (extra group and mixed separator use).

Suggestion: If not already implemented, consider explicitly noting (in the documentation or inline comments) that the validation is case-insensitive so that both uppercase and lowercase hexadecimal digits are accepted.

@sumit6499
Copy link
Author

@colinhacks I’ve reviewed the suggestions from CodeRabbit AI and I’m aware of the lint stage failure in actions. I’ll fix the lint issues, but I’d like to confirm whether I should also incorporate the AI-suggested changes or just focus on resolving the lint errors before updating the PR.

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.

Add support for MAC Address validation
3 participants