Skip to content

Conversation

@guoyunhe
Copy link

@guoyunhe guoyunhe commented Jan 6, 2026

Support various typical phone number formats:

13156451303
131-5645-1303
+8613156451303
+86 131 5645 1303
(123) 456-7890

Summary by CodeRabbit

  • 新功能
    • 添加对电话号码(tel)类型的验证支持,表单验证现在能识别并校验多种电话号码格式。
  • 测试
    • 新增电话号码验证测试套件,覆盖国内/国际格式、带空格/短横/括号等多种情况,并验证必填与非必填行为。

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Jan 6, 2026

Walkthrough

添加对电话号码类型 tel 的完整验证支持:接口类型、验证规则与正则、校验消息、工具函数识别、导出别名和相关测试用例,且在 README 中补充了文档说明。

Changes

Cohort / File(s) 变更摘要
接口与类型定义
src/interface.ts
RuleType 中新增 'tel';在 ValidateMessages.types 中添加 tel 消息字段。
验证消息
src/messages.ts
types 下新增 tel: '%s is not a valid %s' 验证消息条目。
验证规则实现
src/rule/type.ts
新增 pattern.tel 正则与 tel 验证器(长度上限 32,基于 regex);将 'tel' 纳入自定义规则列表。
工具函数
src/util.ts
isNativeStringType() 中加入对 'tel' 的识别(与其他字符串类型一致处理)。
公共导出
src/validator/index.ts
在默认导出对象中添加 tel: type,以暴露新的验证类型别名。
文档
README.md
在 API 文档 Type 部分新增 tel 类型说明。
测试套件
tests/tel.spec.ts
新增测试覆盖非必填空串、国内/国际号码格式、空格/连字符变体、重复空格/连字符拒绝及必填行为等场景。

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 小兔拨号又跑来,
新增 tel 类型真自在,
正则守门把关好,
测试覆盖不含糊,
☎️ 代码上线蹦跶开!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed 拉取请求标题准确总结了主要变更:添加了对电话号码验证器类型的支持,与变更集的核心目标一致。
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link

Summary of Changes

Hello @guoyunhe, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new tel validator, significantly expanding the library's data validation capabilities. This new type allows for robust validation of telephone numbers, accommodating diverse international and local formats, thereby improving data integrity and user input handling.

Highlights

  • New tel validator type: A new validator type tel has been introduced to validate telephone numbers.
  • Support for various phone number formats: The tel validator supports diverse formats including plain numbers, numbers with country codes (e.g., '+8613156451303'), and numbers with spaces, brackets, and dashes (e.g., '+86 131 5645 1303', '(123) 456-7890').
  • Documentation and type definition updates: The README.md has been updated to include the new tel validator type, and src/interface.ts now includes tel in RuleType and ValidateMessages.
  • Regex implementation and length constraint: A new regular expression for telephone numbers has been added in src/rule/type.ts along with validation logic that includes a maximum length of 32 characters.
  • Comprehensive unit tests: A new test file tests/tel.spec.ts has been added to cover various valid and invalid telephone number scenarios, ensuring the reliability of the new validator.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request introduces a new tel validator, which is a useful addition. The changes correctly integrate the new type across the README.md, src/interface.ts, src/messages.ts, src/util.ts, and src/validator/index.ts files. A new test file tests/tel.spec.ts has been added with several test cases covering various phone number formats and the required rule. However, there is a potential issue with the arbitrary length limit imposed on phone numbers, which could lead to valid international numbers being rejected.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds support for a new tel type validator to handle phone number validation. The implementation follows the existing pattern used by other type validators like email and url.

Key Changes:

  • Adds a new telephone number validator with regex-based validation supporting international formats
  • Implements validation for various phone number formats including country codes, brackets, spaces, dots, and dashes
  • Integrates the new validator across all necessary files (validator registry, type system, messages, and documentation)

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/tel.spec.ts Adds test suite covering various valid phone number formats (Chinese and US styles)
src/validator/index.ts Registers the new tel validator in the validator exports
src/util.ts Adds tel to the list of native string types for empty value handling
src/rule/type.ts Implements the core validation logic with regex pattern and 32-character limit
src/messages.ts Adds error message template for invalid telephone numbers
src/interface.ts Adds tel to the RuleType union and ValidateMessages interface
README.md Documents the new tel type in the usage guide

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 1 to 102
import Schema from '../src';

describe('tel', () => {
it('works for empty string', done => {
new Schema({
v: {
type: 'tel',
},
}).validate(
{
v: '',
},
errors => {
expect(errors).toBe(null);
done();
},
);
});

it('works for china mobile phone number', done => {
new Schema({
v: {
type: 'tel',
},
}).validate(
{
v: '13156451303',
},
errors => {
expect(errors).toBe(null);
done();
},
);
});

it('works for china mobile phone number with country code', done => {
new Schema({
v: {
type: 'tel',
},
}).validate(
{
v: '+8613156451303',
},
errors => {
expect(errors).toBe(null);
done();
},
);
});

it('works for china mobile phone number with spaces', done => {
new Schema({
v: {
type: 'tel',
},
}).validate(
{
v: '+86 131 5645 1303',
},
errors => {
expect(errors).toBe(null);
done();
},
);
});

it('works for us phone number with brackets, dashes, and spaces', done => {
new Schema({
v: {
type: 'tel',
},
}).validate(
{
v: '(123) 456-7890',
},
errors => {
expect(errors).toBe(null);
done();
},
);
});

it('works for required empty string', done => {
new Schema({
v: {
type: 'tel',
required: true,
},
}).validate(
{
v: '',
},
errors => {
expect(errors.length).toBe(1);
expect(errors[0].message).toBe('v is required');
done();
},
);
});

});
Copy link

Copilot AI Jan 6, 2026

Choose a reason for hiding this comment

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

The test suite lacks negative test cases to verify that invalid phone numbers are properly rejected. Consider adding test cases for invalid inputs such as:

  • Invalid formats like "abc123" or "123abc"
  • Single digit inputs like "1" or "12"
  • Only special characters like "---" or " "
  • Too long or too short phone numbers
  • Invalid character combinations

Other type validators in the codebase (e.g., url.spec.ts) include negative test cases to ensure invalid inputs are rejected. This helps ensure the regex pattern works correctly and catches edge cases.

Copilot uses AI. Check for mistakes.
src/rule/type.ts Outdated
* @see https://regexr.com/3c53v
* @see https://ihateregex.io/expr/phone/
*/
tel: /^(\+[0-9]{1,3}[-\s\.]?)?(\([0-9]{1,4}\))?[-\s\.0-9]+$/,
Copy link

Copilot AI Jan 6, 2026

Choose a reason for hiding this comment

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

The phone number regex pattern is too permissive and will accept invalid inputs. The pattern uses [-\s\.0-9]+$ as the main number part, which allows:

  • Single digit numbers like "1" or "12"
  • Only special characters like "---" or "..." or " "
  • Any combination of digits, spaces, dots, and dashes without requiring actual digits

Consider strengthening the regex to require:

  • A minimum number of actual digits (e.g., at least 7-10 digits depending on requirements)
  • At least one digit in the main number part to prevent inputs like "---" from being valid
  • More specific formatting rules if you want to enforce stricter validation

A more robust pattern might ensure that there are actual digits present and not just separators.

Suggested change
tel: /^(\+[0-9]{1,3}[-\s\.]?)?(\([0-9]{1,4}\))?[-\s\.0-9]+$/,
tel: /^(\+[0-9]{1,3}[-\s.]?)?(?:\([0-9]{1,4}\))?(?:[-\s.]?\d){7,}$/,

Copilot uses AI. Check for mistakes.
return typeof value === 'string' && value.length <= 320 && !!value.match(pattern.email);
},
tel(value: Value) {
return typeof value === 'string' && value.length <= 32 && !!value.match(pattern.tel);
Copy link

Copilot AI Jan 6, 2026

Choose a reason for hiding this comment

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

The 32 character limit for phone numbers might be too restrictive for some international phone number formats that include country codes, area codes, and extensions. Consider whether this limit is appropriate for your use case. For reference, the E.164 standard allows up to 15 digits, but with formatting characters (spaces, dashes, parentheses, plus sign), phone numbers could legitimately exceed 32 characters, especially with extensions.

Suggested change
return typeof value === 'string' && value.length <= 32 && !!value.match(pattern.tel);
return typeof value === 'string' && value.length <= 64 && !!value.match(pattern.tel);

Copilot uses AI. Check for mistakes.
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: 1

🤖 Fix all issues with AI Agents
In @src/rule/type.ts:
- Around line 15-20: The tel regex on the tel property allows only-separator
strings to match because the final character class [-\s\.0-9]+ can be satisfied
without digits; update the tel pattern to require at least one digit (e.g.,
ensure a lookahead like (?=.*\d) or require \d somewhere in the main pattern)
or, if you prefer not to change the regex, add a numeric check in the tel
validation function (tel()): after the regex test, assert that the value
contains at least one digit (/\d/). Target the tel property in src/rule/type.ts
and/or the tel() validator function to implement one of these fixes.
🧹 Nitpick comments (2)
README.md (1)

186-186: 建议:补充 tel 类型的格式说明

文档条目的格式与其他类型保持一致。不过,考虑到电话号码格式的多样性,建议添加更详细的说明,例如支持的格式示例。

🔎 建议的文档改进
-- `tel`: Must be of type `tel`.
+- `tel`: Must be of type `tel`. Supports various phone number formats with optional country code (e.g., `+86`), area code in parentheses (e.g., `(123)`), and separators (spaces, dashes, dots).

或者,可以在文档中添加一个单独的小节来详细说明 tel 类型支持的格式,类似于其他复杂类型的处理方式。

tests/tel.spec.ts (1)

20-82: 应补充无效电话号码格式的测试用例以完善覆盖范围。

当前测试仅验证了有效的电话号码格式。建议添加测试用例以确保验证器正确拒绝以下无效输入:

  • 包含字母或特殊符号的输入(如 abc123
  • 仅包含分隔符的输入(如 ---
  • 超短或无效的格式组合
建议的补充测试用例
it('should reject phone number with letters', done => {
  new Schema({
    v: {
      type: 'tel',
    },
  }).validate(
    {
      v: 'abc123',
    },
    errors => {
      expect(errors.length).toBe(1);
      done();
    },
  );
});

it('should reject phone number with only separators', done => {
  new Schema({
    v: {
      type: 'tel',
    },
  }).validate(
    {
      v: '---',
    },
    errors => {
      expect(errors.length).toBe(1);
      done();
    },
  );
});
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0a02b9d and 4c33ac0.

📒 Files selected for processing (7)
  • README.md
  • src/interface.ts
  • src/messages.ts
  • src/rule/type.ts
  • src/util.ts
  • src/validator/index.ts
  • tests/tel.spec.ts
🧰 Additional context used
🧬 Code graph analysis (1)
src/rule/type.ts (1)
src/interface.ts (1)
  • Value (182-182)
🔇 Additional comments (9)
src/rule/type.ts (2)

83-96: 实现正确!

'tel' 已正确添加到自定义类型数组中,这样 rule.type === 'tel' 就会通过 types 映射进行验证。实现与现有类型验证器的集成方式保持一致。


67-69: 补充测试覆盖以确保边界情况完整

函数结构正确,现有测试已覆盖空字符串、国际格式和各种分隔符场景。但仍需补充以下测试用例:

  • 32 字符长度限制的边界测试
  • 超出 32 字符的字符串(应返回错误)
  • 仅分隔符的字符串(如 "---"" ",当前正则可能误判为有效)
  • 无数字但包含有效分隔符的字符串

建议扩展 tests/tel.spec.ts 的测试覆盖范围以验证这些边界场景。

src/messages.ts (1)

26-26: 实现正确!

错误消息 '%s is not a valid %s' 与其他类型验证消息(如 email、url、hex)的格式保持一致。格式化后的消息将清晰地指示字段验证失败。

src/validator/index.ts (1)

33-33: 实现正确!

tel: type 添加到导出对象中的方式与现有的 urlhexemail 验证器保持一致。这样用户就可以在验证规则中使用 type: 'tel' 了。

src/util.ts (1)

87-97: 实现正确!

'tel' 添加到 isNativeStringType 检查中是正确的做法。这确保了:

  • tel 类型的值被视为原生字符串类型(与 email、url 等一致)
  • 空字符串在非必填时会被 isEmptyValue 正确识别为空值
  • 验证流程与其他字符串类型保持一致
src/interface.ts (2)

18-18: 变更看起来不错!

将 'tel' 添加到 RuleType 联合类型中,位置合理,与其他通信相关类型(如 'email'、'url')保持一致。


150-150: 类型定义正确!

为 ValidateMessages.types 添加 tel 消息的类型定义,签名与其他类型验证器保持一致。

tests/tel.spec.ts (2)

4-18: 测试逻辑正确!

空字符串在非必填时通过验证,这是标准的验证器行为。


84-100: 必填验证测试正确!

正确测试了当字段为必填时,空字符串应产生验证错误。

@zombieJ
Copy link
Member

zombieJ commented Jan 6, 2026

@gemini-code-assist 请重新 CR,使用中文评论。主要看看正则表达式是否有问题,是否需要优化。

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new tel validator for phone numbers. The changes are well-structured and cover type definitions, validation logic, and documentation. However, I've found a couple of areas for improvement. The regular expression for phone number validation is too permissive and can accept invalid inputs like strings containing only spaces or dashes. I've suggested a fix to make it more robust. Additionally, the new test suite only includes positive test cases for valid phone numbers. I recommend adding negative test cases to ensure the validator correctly rejects invalid formats. Overall, this is a great addition, and with these changes, it will be even more reliable.

@codecov
Copy link

codecov bot commented Jan 6, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.41%. Comparing base (0a02b9d) to head (e63d851).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master      #21      +/-   ##
==========================================
+ Coverage   82.33%   82.41%   +0.08%     
==========================================
  Files          25       25              
  Lines         651      654       +3     
  Branches      232      234       +2     
==========================================
+ Hits          536      539       +3     
  Misses        114      114              
  Partials        1        1              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zombieJ zombieJ merged commit c53cb35 into react-component:master Jan 8, 2026
6 checks passed
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.

2 participants