Skip to content

Phone validate#1515

Merged
AashishBhatt5 merged 7 commits into
developmentfrom
phone-validate
May 27, 2026
Merged

Phone validate#1515
AashishBhatt5 merged 7 commits into
developmentfrom
phone-validate

Conversation

@AashishBhatt5
Copy link
Copy Markdown
Contributor

@AashishBhatt5 AashishBhatt5 commented Apr 16, 2026

What do you want to achieve?

  • Adding Validation in Pre chat lead form.
Screenshot 2026-05-10 at 4 09 42 PM

PR Checklist

  • I have tested it locally and all functionalities are working fine.
  • I have compared it with mocks and all design elements are the same.
  • I have tested it in IE Browser.

How was the code tested?

What new thing you came across while writing this code?

In case you fixed a bug then please describe the root cause of it?

Screenshot

NOTE: Make sure you're comparing your branch with the correct base branch

Summary by CodeRabbit

  • New Features

    • Per-field custom validation (regex + custom error text) for inputs.
    • New full-form validation API that validates visible fields and reports the first error.
    • Inline validation now runs on input/blur after the first submit attempt.
  • Bug Fixes

    • Submission is blocked earlier when pre-chat validation fails.
    • More consistent phone validation and clearer inline feedback.

Review Change Stack

@chatgpt-codex-connector
Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Credits must be used to enable repository wide code reviews.

Comment on lines +599 to +601
var fieldValue = getPreChatInputValue(field);
if (field.hasAttribute('required') && !fieldValue) {
return getLeadCollectionLabel('commonErrorMsg', '');
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: If the labels object in appOptions is completely replaced with an incomplete set, form validation can be silently bypassed because required error messages are missing.
Severity: LOW

Suggested Fix

Ensure validation logic is independent of the presence of a label string. The validation function should return a clear status (e.g., boolean), and the UI logic should handle displaying an error message separately. Alternatively, fall back to a hardcoded, generic error message if a specific label is not found during a validation failure.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: webplugin/js/app/prechat/km-prechat.js#L599-L601

Potential issue: The validation logic for the pre-chat form relies on error message
labels being present in the configuration. If a user provides a severely misconfigured
`appOptions` object that completely replaces the default `labels` object with an
incomplete one (missing keys like `commonErrorMsg`), the validation for fields like
phone number will fail silently. This is because the code checks for the presence of the
error message string before displaying it, and if the string is empty, no error is
shown, allowing the user to proceed with invalid data. While this is an edge case, as
the system is designed to deep-merge configurations, it is technically possible.

Also affects:

  • webplugin/js/app/prechat/km-prechat.js:604~606
  • webplugin/js/app/prechat/km-prechat.js:625~627
  • webplugin/js/app/prechat/km-prechat.js:643~645

Did we get this right? 👍 / 👎 to inform future reviews.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Check this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It will take default error msg

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 16, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1bf0bcbc-f2b5-4291-a97d-1ca0195f1987

📥 Commits

Reviewing files that changed from the base of the PR and between 16319d6 and 86b4fe2.

📒 Files selected for processing (1)
  • webplugin/js/app/mck-sidebox-1.0.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • webplugin/js/app/mck-sidebox-1.0.js

Walkthrough

Centralizes pre-chat validation: adds per-field regex attributes, shared validation helpers and a new target.validatePreChatForm(), updates inline event wiring and submit gating, and removes legacy phone keydown attach/detach calls.

Changes

Pre-Chat Validation Refactoring

Layer / File(s) Summary
Per-field attributes
webplugin/js/app/prechat/km-prechat.js
Adds data-validation-regex and data-validation-error-text to created input controls when preLeadCollection.validation.regex exists (non-select inputs).
Core validation logic
webplugin/js/app/prechat/km-prechat.js
Implements shared helpers for error node management, value extraction, visibility checks, phone validation (intlTel fallback), and adds target.validatePreChatForm() to validate visible .km-form-control fields and return pass/fail.
Inline validation wiring
webplugin/js/app/prechat/km-prechat.js
Updates addPreChatInlineValidation() to wire input/blur events to call validatePreChatForm() after submit; removes registering the old keydown phoneNumberValidation handler in addPhoneNumberValidation().
Submit-time gating
webplugin/js/app/mck-sidebox-1.0.js
Submit handler computes hasPreChatError from the error node and calls validatePreChatForm(), returning false to prevent submission on validation failure; removes a prior call that detached the phone keydown listener.

Sequence Diagram

sequenceDiagram
    actor User
    participant Sidebox as Sidebox Submit
    participant PreChat as PreChat Module
    participant DOM as Form Elements & Error Display

    User->>Sidebox: Submit form
    Sidebox->>DOM: Read error node visibility/text
    Sidebox->>PreChat: Call validatePreChatForm()
    PreChat->>DOM: Iterate visible form controls
    loop For each field
        PreChat->>DOM: Read field value & attrs
        PreChat->>PreChat: Validate (required/email/regex/phone)
        alt Validation fails
            PreChat->>DOM: Set error message on error display
            PreChat->>PreChat: Return false
        end
    end
    PreChat-->>Sidebox: Validation result
    alt Validation passed
        Sidebox->>DOM: Allow submission
    else Validation failed
        Sidebox->>Sidebox: Return false (prevent submission)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Suggested reviewers

  • ayush-kommunicate
  • kandpal025
🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is largely incomplete with most template sections unfilled; only the objective and a screenshot were provided, while testing details, design comparison, browser testing, and other important information remain empty. Complete the PR checklist items, specify testing details, mention any new learnings, and clarify if this fixes a bug. Provide concrete information on how the code was tested and verified.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Phone validate' is vague and does not clearly convey the specific changes made; it lacks descriptive detail about adding validation to the pre-chat lead form. Consider using a more descriptive title like 'Add phone number validation to pre-chat form' to clearly summarize the main change.
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch phone-validate

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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.

Copy link
Copy Markdown
Contributor

@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

🧹 Nitpick comments (1)
webplugin/js/app/prechat/km-prechat.js (1)

611-623: Silent failure on invalid regex could allow unvalidated input.

When new RegExp(validationRegex) throws (line 613-615), regex is set to null and the validation silently passes (line 617 requires regex to be truthy). This means a misconfigured regex pattern would effectively disable validation for that field without any indication.

Consider logging a warning to help administrators identify configuration issues:

Suggested improvement
                 try {
                     regex = new RegExp(validationRegex);
                 } catch (e) {
+                    console.warn('Invalid validation regex for field:', field.id, e.message);
                     regex = null;
                 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@webplugin/js/app/prechat/km-prechat.js` around lines 611 - 623, The current
try/catch around new RegExp(validationRegex) swallows RegExp syntax errors and
allows validation to silently pass; update the catch to log a warning that
includes the offending validationRegex and the caught error (e.g., using
console.warn or the existing logger) and then treat the field as invalid (return
the field's data-validation-error-text or
getLeadCollectionLabel('commonErrorMsg','')) instead of setting regex to null
and skipping validation; locate the logic around new RegExp(validationRegex),
the regex variable, fieldValue, and the existing return that uses
getLeadCollectionLabel to implement this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@webplugin/js/app/mck-sidebox-1.0.js`:
- Around line 4995-4998: The branch in MckMessageService incorrectly checks
_this.validatePreChatForm (which is not set there); update the code so the
actual validator attached by mckInit is invoked: either (a) call the validator
directly from the KMPreChat attachment (e.g. use KMPreChat.validatePreChatForm()
or the function reference created by KMPreChat.attach(...) inside this branch)
or (b) during mckInit assign the validator onto the service (e.g. set
MckMessageService.validatePreChatForm = KMPreChat.validatePreChatForm) and then
use that service property; specifically modify the conditional that references
_this.validatePreChatForm and ensure it invokes the validator function provided
by KMPreChat.attach(...) (validatePreChatForm) so pre-chat validation actually
runs before submitting.

---

Nitpick comments:
In `@webplugin/js/app/prechat/km-prechat.js`:
- Around line 611-623: The current try/catch around new RegExp(validationRegex)
swallows RegExp syntax errors and allows validation to silently pass; update the
catch to log a warning that includes the offending validationRegex and the
caught error (e.g., using console.warn or the existing logger) and then treat
the field as invalid (return the field's data-validation-error-text or
getLeadCollectionLabel('commonErrorMsg','')) instead of setting regex to null
and skipping validation; locate the logic around new RegExp(validationRegex),
the regex variable, fieldValue, and the existing return that uses
getLeadCollectionLabel to implement this change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f0859aab-5e7f-4887-867e-02f605fff321

📥 Commits

Reviewing files that changed from the base of the PR and between 75ccc9e and 729e512.

📒 Files selected for processing (2)
  • webplugin/js/app/mck-sidebox-1.0.js
  • webplugin/js/app/prechat/km-prechat.js

Comment thread webplugin/js/app/mck-sidebox-1.0.js
Copy link
Copy Markdown
Contributor

@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

🧹 Nitpick comments (1)
webplugin/js/app/prechat/km-prechat.js (1)

746-771: ⚡ Quick win

Make inline validation listener binding idempotent.

target.addPreChatInlineValidation adds anonymous input/blur/click listeners every call. If this initializer runs again, handlers stack and validation fires multiple times per event.

Proposed fix
         target.addPreChatInlineValidation = function () {
             var form = document.getElementById('km-form-chat-login');
             var submitBtn = document.getElementById('km-submit-chat-login');
+            if (form && form.getAttribute('data-prechat-validation-bound') === 'true') {
+                return;
+            }
+            if (form) {
+                form.setAttribute('data-prechat-validation-bound', 'true');
+            }
             var formSubmitted = false;
             var formFields = form ? form.querySelectorAll('.km-form-control') : [];
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@webplugin/js/app/prechat/km-prechat.js` around lines 746 - 771, The
addPreChatInlineValidation function currently attaches anonymous
input/blur/click handlers each time it's called, causing duplicate handlers; to
fix, make binding idempotent by detecting and skipping if already bound (e.g.,
check a flag or element dataset/property) or attach named handler functions and
remove existing listeners before adding; update
target.addPreChatInlineValidation to use stable handler functions (referencing
target.validatePreChatForm) and set a marker on the form or submitBtn (e.g.,
form.__kmInlineValidationBound or form.dataset.kmBound) after initial binding so
subsequent calls do nothing.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@webplugin/js/app/prechat/km-prechat.js`:
- Around line 701-708: The current catch swallows invalid regex and lets
validation pass; instead when RegExp(validationRegex) throws, mark the field as
invalid (fail closed) by setting a failure flag or forcing the regex to never
match and add a validation error for that field; specifically, inside the catch
for new RegExp(validationRegex) update the validation outcome for field (use the
same field, fieldValue, validationRegex, regex symbols) to produce a fallback
error message and log the parsing exception so the invalid config does not
silently disable validation.

---

Nitpick comments:
In `@webplugin/js/app/prechat/km-prechat.js`:
- Around line 746-771: The addPreChatInlineValidation function currently
attaches anonymous input/blur/click handlers each time it's called, causing
duplicate handlers; to fix, make binding idempotent by detecting and skipping if
already bound (e.g., check a flag or element dataset/property) or attach named
handler functions and remove existing listeners before adding; update
target.addPreChatInlineValidation to use stable handler functions (referencing
target.validatePreChatForm) and set a marker on the form or submitBtn (e.g.,
form.__kmInlineValidationBound or form.dataset.kmBound) after initial binding so
subsequent calls do nothing.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9dac262e-d6ac-4fce-aee6-81fb6bf36208

📥 Commits

Reviewing files that changed from the base of the PR and between 729e512 and d26a1ab.

📒 Files selected for processing (2)
  • webplugin/js/app/mck-sidebox-1.0.js
  • webplugin/js/app/prechat/km-prechat.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • webplugin/js/app/mck-sidebox-1.0.js

Comment thread webplugin/js/app/prechat/km-prechat.js
Copy link
Copy Markdown

@ayush-kommunicate ayush-kommunicate left a comment

Choose a reason for hiding this comment

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

Check AI comment once any change required or not.

@AashishBhatt5 AashishBhatt5 merged commit 8e2a1cd into development May 27, 2026
1 of 3 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