Skip to content

[774] fix: Improve phone number validation error messages - #209

Merged
VitalyyP merged 7 commits into
mainfrom
774-fix/phone-number-validation
Aug 17, 2025
Merged

[774] fix: Improve phone number validation error messages#209
VitalyyP merged 7 commits into
mainfrom
774-fix/phone-number-validation

Conversation

@VitalyyP

@VitalyyP VitalyyP commented Aug 8, 2025

Copy link
Copy Markdown
Contributor
  • Simplify phone number validation logic using formatPhoneNumber function
  • Update test cases to match new error message format
  • Improve validation schema to use min/max length constraints instead of complex regex patterns

@VitalyyP
VitalyyP requested a review from killev as a code owner August 8, 2025 16:11
@coderabbitai

coderabbitai Bot commented Aug 8, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Phone-number validation was refactored: the PHONE_NUMBER schema now trims input, rejects alphabetic characters early, enforces digits count between 10 and 15 with explicit "Phone number is too short"/"Phone number is too long" errors, and delegates formatting/validation to an imported formatPhoneNumber function. Tests in formValidator.test.js, phoneNumberValidator.test.js, and validationSchemas.test.js were updated to expect simplified or more specific error messages and some tests now call validation directly rather than using a helper.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Suggested reviewers

  • yuramax
  • Anton-88
  • IhorMasechko

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 774-fix/phone-number-validation

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@VitalyyP VitalyyP changed the title fix: Improve phone number validation error messages [774] fix: Improve phone number validation error messages Aug 8, 2025
@github-actions

github-actions Bot commented Aug 8, 2025

Copy link
Copy Markdown

🔍 Vulnerabilities of apostrophe-cms:test

📦 Image Reference apostrophe-cms:test
digestsha256:a21a3d5a0b18fa56ae00491dba7b68ac957ec6c06ca0e013306079ef1aaa2b7a
vulnerabilitiescritical: 1 high: 4 medium: 0 low: 0
platformlinux/amd64
size291 MB
packages984
📦 Base Image node:23-alpine
also known as
  • 23-alpine3.22
  • 23.11-alpine
  • 23.11-alpine3.22
  • 23.11.1-alpine
  • 23.11.1-alpine3.22
digestsha256:b9d38d589853406ff0d4364f21969840c3e0397087643aef8eede40edbb6c7cd
vulnerabilitiescritical: 0 high: 0 medium: 1 low: 1
critical: 1 high: 0 medium: 0 low: 0 form-data 4.0.2 (npm)

pkg:npm/form-data@4.0.2

critical 9.4: CVE--2025--7783 Use of Insufficiently Random Values

Affected range>=4.0.0
<4.0.4
Fixed version4.0.4
CVSS Score9.4
CVSS VectorCVSS:4.0/AV:N/AC:H/AT:N/PR:N/UI:N/VC:H/VI:H/VA:N/SC:H/SI:H/SA:N
EPSS Score0.076%
EPSS Percentile23rd percentile
Description

Summary

form-data uses Math.random() to select a boundary value for multipart form-encoded data. This can lead to a security issue if an attacker:

  1. can observe other values produced by Math.random in the target application, and
  2. can control one field of a request made using form-data

Because the values of Math.random() are pseudo-random and predictable (see: https://blog.securityevaluators.com/hacking-the-javascript-lottery-80cc437e3b7f), an attacker who can observe a few sequential values can determine the state of the PRNG and predict future values, includes those used to generate form-data's boundary value. The allows the attacker to craft a value that contains a boundary value, allowing them to inject additional parameters into the request.

This is largely the same vulnerability as was recently found in undici by parrot409 -- I'm not affiliated with that researcher but want to give credit where credit is due! My PoC is largely based on their work.

Details

The culprit is this line here: https://github.com/form-data/form-data/blob/426ba9ac440f95d1998dac9a5cd8d738043b048f/lib/form_data.js#L347

An attacker who is able to predict the output of Math.random() can predict this boundary value, and craft a payload that contains the boundary value, followed by another, fully attacker-controlled field. This is roughly equivalent to any sort of improper escaping vulnerability, with the caveat that the attacker must find a way to observe other Math.random() values generated by the application to solve for the state of the PRNG. However, Math.random() is used in all sorts of places that might be visible to an attacker (including by form-data itself, if the attacker can arrange for the vulnerable application to make a request to an attacker-controlled server using form-data, such as a user-controlled webhook -- the attacker could observe the boundary values from those requests to observe the Math.random() outputs). A common example would be a x-request-id header added by the server. These sorts of headers are often used for distributed tracing, to correlate errors across the frontend and backend. Math.random() is a fine place to get these sorts of IDs (in fact, opentelemetry uses Math.random for this purpose)

PoC

PoC here: https://github.com/benweissmann/CVE-2025-7783-poc

Instructions are in that repo. It's based on the PoC from https://hackerone.com/reports/2913312 but simplified somewhat; the vulnerable application has a more direct side-channel from which to observe Math.random() values (a separate endpoint that happens to include a randomly-generated request ID).

Impact

For an application to be vulnerable, it must:

  • Use form-data to send data including user-controlled data to some other system. The attacker must be able to do something malicious by adding extra parameters (that were not intended to be user-controlled) to this request. Depending on the target system's handling of repeated parameters, the attacker might be able to overwrite values in addition to appending values (some multipart form handlers deal with repeats by overwriting values instead of representing them as an array)
  • Reveal values of Math.random(). It's easiest if the attacker can observe multiple sequential values, but more complex math could recover the PRNG state to some degree of confidence with non-sequential values.

If an application is vulnerable, this allows an attacker to make arbitrary requests to internal systems.

critical: 0 high: 1 medium: 0 low: 0 async 0.9.2 (npm)

pkg:npm/async@0.9.2

high 7.8: CVE--2021--43138 OWASP Top Ten 2017 Category A9 - Using Components with Known Vulnerabilities

Affected range<2.6.4
Fixed version2.6.4, 3.2.2
CVSS Score7.8
CVSS VectorCVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score0.907%
EPSS Percentile75th percentile
Description

A vulnerability exists in Async through 3.2.1 (fixed in 3.2.2), which could let a malicious user obtain privileges via the mapValues() method.

critical: 0 high: 1 medium: 0 low: 0 linkifyjs 4.2.0 (npm)

pkg:npm/linkifyjs@4.2.0

high 8.8: CVE--2025--8101 Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')

Affected range<4.3.2
Fixed version4.3.2
CVSS Score8.8
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:H/VA:L/SC:N/SI:N/SA:N
EPSS Score0.060%
EPSS Percentile19th percentile
Description

Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') vulnerability in Linkify (linkifyjs) allows XSS Targeting HTML Attributes and Manipulating User-Controlled Variables.This issue affects Linkify: from 4.3.1 before 4.3.2.

critical: 0 high: 1 medium: 0 low: 0 connect-multiparty 2.2.0 (npm)

pkg:npm/connect-multiparty@2.2.0

high 7.8: CVE--2022--29623 Unrestricted Upload of File with Dangerous Type

Affected range<=2.2.0
Fixed versionNot Fixed
CVSS Score7.8
CVSS VectorCVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score0.320%
EPSS Percentile54th percentile
Description

An arbitrary file upload vulnerability in the file upload module of Express Connect-Multiparty 2.2.0 allows attackers to execute arbitrary code via a crafted PDF file. NOTE: the Supplier has not verified this vulnerability report.

critical: 0 high: 1 medium: 0 low: 0 async 1.5.2 (npm)

pkg:npm/async@1.5.2

high 7.8: CVE--2021--43138 OWASP Top Ten 2017 Category A9 - Using Components with Known Vulnerabilities

Affected range<2.6.4
Fixed version2.6.4, 3.2.2
CVSS Score7.8
CVSS VectorCVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score0.907%
EPSS Percentile75th percentile
Description

A vulnerability exists in Async through 3.2.1 (fixed in 3.2.2), which could let a malicious user obtain privileges via the mapValues() method.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
website/modules/asset/ui/src/js/formValidator.test.js (1)

17-18: Avoid hard-coding the new error string in multiple places

You updated PHONE_INVALID, but the tests below embed 'Phone number is too short' inline. Expose a PHONE_TOO_SHORT constant (similar to the other message constants) and reuse it here:

+    PHONE_TOO_SHORT: 'Phone number is too short',

and replace the inline literals with the constant. This keeps future copy edits to a single change.

Also applies to: 202-208

website/modules/asset/ui/src/js/validationSchemas.test.js (1)

110-113: Duplicate literal strings across test suites

The literal 'Phone number is too short' and 'Enter a valid phone number' are now repeated across three separate test files. Consider importing the same message constants used by the validator so that tests stay in sync with the schema wording.

Also applies to: 124-126, 130-132

website/modules/asset/ui/src/js/phoneNumberValidator.test.js (1)

8-9: Keep message sources and helpers consistent

  1. You introduce ERROR_MESSAGE but still hard-code the same string in later assertions. Re-use the constant to avoid accidental drift.

  2. The bespoke assertions in the two middle tests duplicate the logic already encapsulated in expectInvalidPhone. Using the helper keeps the suite DRY and aligned with future message tweaks.

Refactor example:

-  it('rejects invalid international format', async () => {
-    phoneInput.value = '+123';
-    const result = await validateField(phoneInput);
-    expect(result).toEqual({
-      isValid: false,
-      message: ERROR_MESSAGE,
-    });
-  });
+  it('rejects invalid international format', async () =>
+    expectInvalidPhone('+123'));

Also applies to: 35-42, 45-51

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 336cb19 and e62a98b.

📒 Files selected for processing (4)
  • website/modules/asset/ui/src/js/formValidator.test.js (2 hunks)
  • website/modules/asset/ui/src/js/phoneNumberValidator.test.js (2 hunks)
  • website/modules/asset/ui/src/js/validationSchemas.js (2 hunks)
  • website/modules/asset/ui/src/js/validationSchemas.test.js (2 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: yuramax
PR: speedandfunction/website#120
File: website/modules/asset/ui/src/index.js:43-67
Timestamp: 2025-05-26T06:19:32.209Z
Learning: When reviewing PRs focused on styling, defer functional JavaScript improvements to separate tasks to maintain clear scope separation.
Learnt from: yuramax
PR: speedandfunction/website#139
File: website/jest.config.cjs:4-4
Timestamp: 2025-06-03T16:27:46.172Z
Learning: When reviewing PRs, focus suggestions on the main objectives stated in the PR description. Skip suggestions for incidental changes that are unrelated to the PR's primary purpose, especially when the user explicitly requests to stay focused on the main feature/improvement.
📚 Learning: 2025-07-01T07:44:33.034Z
Learnt from: CR
PR: speedandfunction/website#0
File: .cursor/rules/code-conventions.mdc:0-0
Timestamp: 2025-07-01T07:44:33.034Z
Learning: Applies to modules/apostrophecms/form/index.js : modules/apostrophecms/form/index.js: relaxed maximum lines rule

Applied to files:

  • website/modules/asset/ui/src/js/formValidator.test.js
  • website/modules/asset/ui/src/js/validationSchemas.test.js
  • website/modules/asset/ui/src/js/validationSchemas.js
  • website/modules/asset/ui/src/js/phoneNumberValidator.test.js
📚 Learning: 2025-07-01T07:44:33.034Z
Learnt from: CR
PR: speedandfunction/website#0
File: .cursor/rules/code-conventions.mdc:0-0
Timestamp: 2025-07-01T07:44:33.034Z
Learning: Applies to **/*.test.{js,jsx} : Test files have relaxed rules for function length, statements, extraneous requires, and destructuring

Applied to files:

  • website/modules/asset/ui/src/js/phoneNumberValidator.test.js
📚 Learning: 2025-07-01T07:44:33.034Z
Learnt from: CR
PR: speedandfunction/website#0
File: .cursor/rules/code-conventions.mdc:0-0
Timestamp: 2025-07-01T07:44:33.034Z
Learning: Applies to **/*.e2e.{js,jsx} : E2E test files: relaxed import, ternary, and sorting rules

Applied to files:

  • website/modules/asset/ui/src/js/phoneNumberValidator.test.js
🧬 Code Graph Analysis (2)
website/modules/asset/ui/src/js/validationSchemas.js (1)
website/modules/asset/ui/src/js/phoneFormat.js (1)
  • formatPhoneNumber (163-174)
website/modules/asset/ui/src/js/phoneNumberValidator.test.js (1)
website/modules/asset/ui/src/js/formValidator.js (1)
  • validateField (39-74)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: e2e-tests
  • GitHub Check: unit-tests
  • GitHub Check: lint
  • GitHub Check: security-scan

Comment thread website/modules/asset/ui/src/js/validationSchemas.js Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
website/modules/asset/ui/src/js/validationSchemas.js (1)

43-56: Resolved prior concern: length checks now use digit count, with specific messages

Moving min/max into the custom test and counting digits fixes the “raw length vs. digit length” issue and ensures users see “too short/too long.” This also addresses the previous review’s feedback, and the .trim() addition is a plus.

🧹 Nitpick comments (3)
website/modules/asset/ui/src/js/validationSchemas.test.js (1)

81-134: Add trimming and boundary tests for phone numbers

Since .trim() was added to the phone number schema, add a test to confirm whitespace is ignored. Also consider boundary tests for exactly 10 and exactly 15 digits.

Would you like me to open a follow-up PR adding:

  • accepts phone number with surrounding whitespace
  • accepts exactly 10 digits
  • accepts exactly 15 digits

Example tests to add:

test('trims whitespace around phone number', async () => {
  await expect(schema.validate('   (234) 567-8900   ')).resolves.toBe('(234) 567-8900');
});

test('accepts exactly 10 digits', async () => {
  await expect(schema.validate('2345678900')).resolves.toBe('2345678900');
});

test('accepts exactly 15 digits', async () => {
  await expect(schema.validate('+123456789012345')).resolves.toBe('+123456789012345');
});
website/modules/asset/ui/src/js/validationSchemas.js (2)

41-42: Broaden letter detection to all Unicode letters (optional)

/[A-Za-z]/ matches only Latin letters. If you want to block any script’s letters (e.g., Cyrillic, Greek), prefer Unicode properties. Node 12+ supports this.

-      if (/[A-Za-z]/u.test(value)) return false;
+      // Disallow any letter from any script
+      if (/\p{L}/u.test(value)) return false;

If older runtimes must be supported, consider a negative char class allow-list instead (digits and common punctuation only).


58-60: Delegation to formatPhoneNumber is clear

Returning Boolean(formatted) makes the generic “Enter a valid phone number” the fallback for non-digit-length issues. Consider adding unit tests for exactly-10 and exactly-15 digits to cover boundaries (see test-file note).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e62a98b and 4499a27.

📒 Files selected for processing (2)
  • website/modules/asset/ui/src/js/validationSchemas.js (2 hunks)
  • website/modules/asset/ui/src/js/validationSchemas.test.js (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
website/modules/asset/ui/src/js/validationSchemas.test.js (1)
website/modules/asset/ui/src/js/formValidator.js (2)
  • schema (25-25)
  • schema (53-53)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: unit-tests
  • GitHub Check: e2e-tests
  • GitHub Check: security-scan
  • GitHub Check: lint
🔇 Additional comments (6)
website/modules/asset/ui/src/js/validationSchemas.test.js (4)

110-113: Updated message matches new schema behavior

Switch to "Phone number is too short" is consistent with digit-length validation. LGTM.


123-127: Renamed test and simplified message are appropriate

Renaming to “rejects phone number with only letters” and asserting "Enter a valid phone number" aligns with the formatter-first flow.


129-133: Consistent invalid-format message

Using "Enter a valid phone number" for mixed alphanumerics matches the schema’s fallback. Good.


123-127: Ignore trailing-period suggestion for phone number message

Our grep search found no instances of
'Enter a valid phone number.' (with a period). All occurrences use the message without a trailing period:

  • website/modules/asset/ui/src/js/validationSchemas.js (line 39)
  • website/modules/asset/ui/src/js/phoneNumberValidator.test.js (line 49)
  • website/modules/asset/ui/src/js/validationSchemas.test.js (lines 125, 131)
  • website/modules/asset/ui/src/js/formValidator.test.js (line 17)

You can safely ignore this review comment.

Likely an incorrect or invalid review comment.

website/modules/asset/ui/src/js/validationSchemas.js (2)

37-37: Good addition: .trim()

Trimming ensures empty/space-only inputs hit the required check consistently. LGTM.


1-1: No issues with formatPhoneNumber import

The file website/modules/asset/ui/src/js/phoneFormat.js exists and correctly exports a named formatPhoneNumber function alongside initPhoneFormatting. The destructuring import in validationSchemas.js is safe and will not cause runtime errors.

Comment thread website/modules/asset/ui/src/js/validationSchemas.js
@VitalyyP VitalyyP self-assigned this Aug 11, 2025
@VitalyyP
VitalyyP requested a review from Anton-88 August 11, 2025 17:41

@Anton-88 Anton-88 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@VitalyyP
VitalyyP enabled auto-merge (squash) August 14, 2025 10:54
@VitalyyP

Copy link
Copy Markdown
Contributor Author

@coderabbitai re-run

@coderabbitai

coderabbitai Bot commented Aug 14, 2025

Copy link
Copy Markdown
Contributor

@VitalyyP I'll re-run the review for this PR.

✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
website/modules/asset/ui/src/js/validationSchemas.js (1)

39-59: Don’t override “required” error and support non-ASCII letters in the check

Two targeted tweaks:

  • Let .required() surface for empty values to avoid showing “too short” on empty input if abortEarly is disabled upstream.
  • Use Unicode property escapes to catch letters beyond A–Z (e.g., “тест”, “ábč”).
-    .test('phone-format', 'Enter a valid phone number', (value, context) => {
-      if (/[A-Za-z]/u.test(value)) return false;
+    .test('phone-format', 'Enter a valid phone number', (value, context) => {
+      // Defer empty/undefined handling to .required() above
+      if (!value) return true;
+      if (/\p{L}/u.test(value)) return false;

No change needed below for the digit-length checks and format validation.

🧹 Nitpick comments (5)
website/modules/asset/ui/src/js/formValidator.test.js (2)

200-208: Avoid magic strings: reuse a constant for “too short”

The literal "Phone number is too short" is duplicated in this suite. Prefer a constant for consistency and easier future changes.

Apply this diff to use a constant here:

       {
         description: 'rejects too short phone number',
         value: TEST_CONSTANTS.INVALID_SAMPLES.PHONE_SHORT,
-        message: 'Phone number is too short',
+        message: TEST_CONSTANTS.MESSAGES.PHONE_TOO_SHORT,
       },
       {
         description: 'rejects invalid international format',
         value: TEST_CONSTANTS.INVALID_SAMPLES.PHONE_INVALID,
-        message: 'Phone number is too short',
+        message: TEST_CONSTANTS.MESSAGES.PHONE_TOO_SHORT,
       },

And define the constants in the MESSAGES block (outside the selected range):

// Add to TEST_CONSTANTS.MESSAGES
PHONE_TOO_SHORT: 'Phone number is too short',
PHONE_TOO_LONG: 'Phone number is too long',

198-210: Add a “too long” phone validation case to cover the upper bound

We test “too short” here; adding a “too long” case strengthens integration coverage at form level to mirror schema tests.

     additionalTests: [
       {
         description: 'rejects too short phone number',
         value: TEST_CONSTANTS.INVALID_SAMPLES.PHONE_SHORT,
         message: TEST_CONSTANTS.MESSAGES.PHONE_TOO_SHORT,
       },
       {
         description: 'rejects invalid international format',
         value: TEST_CONSTANTS.INVALID_SAMPLES.PHONE_INVALID,
         message: TEST_CONSTANTS.MESSAGES.PHONE_TOO_SHORT,
       },
+      {
+        description: 'rejects too long phone number',
+        value: '1'.repeat(16), // 16 digits
+        message: TEST_CONSTANTS.MESSAGES.PHONE_TOO_LONG,
+      },
     ],
website/modules/asset/ui/src/js/validationSchemas.test.js (1)

123-127: Broaden letter-only rejection to cover non-ASCII letters; add a test

The schema currently checks [A-Za-z]; this misses non-ASCII letters (e.g., “тест”, “ábč”). Consider adding a test to document expected behavior and updating the schema to use Unicode properties.

Add this test (outside the selected range):

test('rejects phone number with only non-ASCII letters', async () => {
  await expect(schema.validate('тест')).rejects.toThrow('Enter a valid phone number');
  await expect(schema.validate('ábč')).rejects.toThrow('Enter a valid phone number');
});

Then update the schema regex to \p{L} (see comment in validationSchemas.js).

website/modules/asset/ui/src/js/phoneNumberValidator.test.js (2)

35-42: Reuse the ERROR_MESSAGE constant to avoid duplication

You already defined ERROR_MESSAGE; use it here too.

   it('rejects invalid international format', async () => {
     phoneInput.value = '+123';
     const result = await validateField(phoneInput);
     expect(result).toEqual({
       isValid: false,
-      message: 'Phone number is too short',
+      message: ERROR_MESSAGE,
     });
   });

44-51: Extract the “invalid” message into a constant for consistency

This keeps message strings centralized in tests.

Apply this change within this block:

 it('rejects phone number with letters', async () => {
   phoneInput.value = '+1 (234) ABC-1234';
   const result = await validateField(phoneInput);
   expect(result).toEqual({
     isValid: false,
-    message: 'Enter a valid phone number',
+    message: INVALID_PHONE_MESSAGE,
   });
 });

And define the constant near ERROR_MESSAGE (outside the selected range):

const INVALID_PHONE_MESSAGE = 'Enter a valid phone number';
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b60dca9 and 10e02ed.

📒 Files selected for processing (4)
  • website/modules/asset/ui/src/js/formValidator.test.js (2 hunks)
  • website/modules/asset/ui/src/js/phoneNumberValidator.test.js (2 hunks)
  • website/modules/asset/ui/src/js/validationSchemas.js (2 hunks)
  • website/modules/asset/ui/src/js/validationSchemas.test.js (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
website/modules/asset/ui/src/js/phoneNumberValidator.test.js (3)
website/modules/asset/ui/src/js/formValidator.test.js (5)
  • result (55-55)
  • result (68-68)
  • result (77-77)
  • result (87-87)
  • result (93-93)
website/modules/asset/ui/src/js/formValidation.test.js (1)
  • validateField (23-23)
website/modules/asset/ui/src/js/formValidator.js (1)
  • validateField (39-74)
website/modules/asset/ui/src/js/validationSchemas.test.js (1)
website/modules/asset/ui/src/js/formValidator.js (2)
  • schema (25-25)
  • schema (53-53)
website/modules/asset/ui/src/js/validationSchemas.js (1)
website/modules/asset/ui/src/js/phoneFormat.js (1)
  • formatPhoneNumber (163-174)
🔇 Additional comments (3)
website/modules/asset/ui/src/js/formValidator.test.js (1)

17-17: Message update aligns with new validation UX — looks good

Switching PHONE_INVALID to the shorter "Enter a valid phone number" matches the updated schema and other tests.

website/modules/asset/ui/src/js/validationSchemas.test.js (2)

110-114: Specific “too short” message assertion is correct

This matches the schema’s digit-count path and ensures the user gets the more actionable error.


129-133: Letters mixed with digits: expectation matches the generic invalid message

Good coverage for non-digit contamination.

@sonarqubecloud

Copy link
Copy Markdown

@VitalyyP
VitalyyP merged commit e29679a into main Aug 17, 2025
12 checks passed
@VitalyyP
VitalyyP deleted the 774-fix/phone-number-validation branch August 17, 2025 08:30
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.

3 participants