Skip to content

[codex] Add pre-chat regex validation support#1522

Open
devashishmamgain wants to merge 3 commits into
developmentfrom
codex/tdh-3656-prechat-validation
Open

[codex] Add pre-chat regex validation support#1522
devashishmamgain wants to merge 3 commits into
developmentfrom
codex/tdh-3656-prechat-validation

Conversation

@devashishmamgain
Copy link
Copy Markdown
Collaborator

@devashishmamgain devashishmamgain commented May 11, 2026

Summary

  • support preLeadCollection validation.regex and validation.errorText from widget script config
  • wire the regex into browser pattern validation and the existing inline pre-chat error area
  • keep existing email and phone validation behavior when no custom regex is configured
  • trim trailing clipboard newlines when pasting copied widget messages back into the composer
  • sort loaded widget messages by createdAtTime before rendering so welcome-message parts keep a deterministic order

Jira

  • TDH-3656
  • TDH-3614
  • TDH-3449

Validation

  • node --check webplugin/js/app/prechat/km-prechat.js
  • node --check webplugin/js/app/mck-sidebox-1.0.js
  • git diff --check

Summary by CodeRabbit

Release Notes

  • New Features

    • Added customizable field validation in pre-chat forms with real-time validation feedback and error messaging.
  • Bug Fixes

    • Fixed text pasting in chat composer to properly handle line breaks and formatting.
    • Improved message ordering consistency during reload flows.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 11, 2026

Walkthrough

Adds per-field regex-driven validation for pre-chat lead inputs (helpers, input wiring, runtime validators, unified submit guard) and normalizes/sorts pasted and loaded messages by createdAtTime in the sidebox composer.

Changes

Pre-chat Custom Field Validation

Layer / File(s) Summary
Validation Configuration Helpers
webplugin/js/app/prechat/km-prechat.js
Adds getCustomValidation and setValidationAttributes to parse preLeadCollection.validation.regex (RegExp or string) and apply pattern/title/data-km-validation-* attributes with oninvalid/oninput handlers.
Input Field Validation Setup
webplugin/js/app/prechat/km-prechat.js
Updates target.createInputField to apply custom validation attributes when configured, otherwise retains email-specific attribute setup.
Custom Fields Discovery
webplugin/js/app/prechat/km-prechat.js
Collects elements annotated with data-km-validation-regex to identify fields requiring custom validation.
Per-field Validation Logic
webplugin/js/app/prechat/km-prechat.js
Adds validateCustomField to evaluate required-state and regex matches, handle invalid regexes, and set/clear shared login error messages.
Validation Orchestration & Listeners
webplugin/js/app/prechat/km-prechat.js
Implements handleCustomValidation to run all custom validators (gated by formSubmitted) and wires input/blur listeners to run validation during interaction.
Email and Phone Validation Consistency
webplugin/js/app/prechat/km-prechat.js
Refactors email and phone validators to return boolean consistently so submit flow can short-circuit on failures.
Submit Handler Integration
webplugin/js/app/prechat/km-prechat.js
Adds unified handleSubmitValidation that runs custom validation first, then email/phone validators, prevents submission on failure, and clears errors on success; both click and form submit use it.

Sidebox Composer: Paste Normalization & Message Sorting

Layer / File(s) Summary
Composer Paste Normalization
webplugin/js/app/mck-sidebox-1.0.js
Normalize pasted clipboard text by converting CRLF to LF and trimming trailing newlines before insertion.
Message Sorting Helper and Usage
webplugin/js/app/mck-sidebox-1.0.js
Adds _this.sortMessagesByCreatedAt(messages, descending) to sort arrays by numeric createdAtTime and updates processMessageList to deterministically sort data.message arrays (including allowReload flows) and adjust scroll handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

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

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description provides a clear summary of changes, lists related Jira issues, and includes validation steps, but does not follow the repository's template structure. Fill out the template sections including 'What do you want to achieve', 'PR Checklist', 'How was the code tested', and relevant decision questions to align with repository standards.
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.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change—adding regex validation support for pre-chat forms—and is concise and specific enough for scanning PR history.
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 codex/tdh-3656-prechat-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

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: 3

🤖 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 736-737: handleCustomValidation currently calls setError('') when
custom fields pass, which can clear unrelated email/phone errors; remove any
setError('') calls from handleCustomValidation (and the identical calls at the
other block around the same logic) so the function only returns true/false.
Instead, clear the global error in the centralized submit chain after all
validators succeed—i.e., in the form submission handler (e.g.,
handleSubmit/onSubmit) call setError('') only once after running
handleCustomValidation and the other validators and confirming they all passed.
- Around line 818-821: The submit flow calls handlePhoneValidation() but ignores
its boolean result, so failed phone validation won't stop submission; update the
submit logic (the block using handleEmailValidation and handlePhoneValidation)
to check the return value of handlePhoneValidation exactly like
handleEmailValidation (e.g., if (handlePhoneValidation &&
!handlePhoneValidation()) return;), or otherwise combine both results and return
early when either validation fails; ensure you reference the existing
handleEmailValidation and handlePhoneValidation functions so behavior remains
consistent.
- Around line 720-723: The catch block that logs "Invalid pre-chat validation
regex" currently returns true (allowing the field), which makes regex parse
failures bypass validation; change that catch to return false so a regex parse
error fails validation (fail-closed) and also invoke the existing user-facing
validation error path (e.g., call the same error/reporting helper used for other
validation failures or push a message to the field's errors array) instead of
silently only logging; update the catch around the console.error('Invalid
pre-chat validation regex', error) to log the error and then trigger the normal
validation-failure flow so users see an error.
🪄 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: 31149cac-f6b7-49d6-8b4d-76bd1ed0108c

📥 Commits

Reviewing files that changed from the base of the PR and between 5c076e7 and 8d1f631.

📒 Files selected for processing (1)
  • webplugin/js/app/prechat/km-prechat.js

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8d1f6316f4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread webplugin/js/app/prechat/km-prechat.js Outdated
Comment on lines +815 to +816
if (!handleCustomValidation()) {
return;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Prevent submit when custom validation fails

When a custom regex is configured on a textarea pre-chat field, pattern is not enforced by native HTML constraint validation, so this return only exits the click listener while the form still proceeds to the existing #km-form-chat-login submit handler and initializes the chat with the invalid value. Pass the click event into the handler and call preventDefault() (or move the custom check into the submit handler) whenever handleCustomValidation() returns false.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 68b900451f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +368 to +369
if (regex instanceof RegExp) {
regex = regex.source;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve validation regex flags

When a widget config passes validation.regex as a RegExp with flags, such as /^[a-z]+$/i for a case-insensitive field, converting it to regex.source drops the flags before both the pattern attribute and data-km-validation-regex are populated. Those fields then become case-sensitive and reject values that the configured validator was meant to accept, so either preserve the flags for the JS check or avoid accepting RegExp objects without flag handling.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b7f299a5bb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (!input || !validation || !validation.regex) {
return;
}
input.setAttribute('pattern', validation.regex);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve flags in native validation

Although the new data attribute now preserves RegExp flags for the JS check, this line still installs only the regex source as the HTML pattern. For a configured validator like /^[a-z]+$/i, entering ABC passes handleCustomValidation() but the browser’s native pattern check is case-sensitive and prevents the form submit before the submit listener can proceed, so values accepted by the supplied validator remain blocked.

Useful? React with 👍 / 👎.

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

🤖 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/mck-sidebox-1.0.js`:
- Around line 4366-4369: The current assignment to text calls (e.clipboardData
|| window.clipboardData).getData('text') directly which can throw when clipboard
APIs are absent; change it to first capture the data source (e.clipboardData ||
window.clipboardData), check that it's truthy, call getData('text') only when
present, and then run the .replace(...) on a safe string (e.g., raw || '') so
that e.clipboardData/window.clipboardData and getData are guarded; update the
assignment where text is computed (the const text = ... line) to use this safe
pattern referencing e.clipboardData, window.clipboardData and getData.
🪄 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: 84732426-1245-4aa8-a78e-9d835518cf35

📥 Commits

Reviewing files that changed from the base of the PR and between 8d1f631 and b7f299a.

📒 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/prechat/km-prechat.js

Comment on lines +4366 to +4369
const text = (e.clipboardData || window.clipboardData)
.getData('text')
.replace(/\r\n/g, '\n')
.replace(/\n+$/, '');
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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard clipboard access before calling getData()

Line 4366 can throw when clipboard APIs are unavailable, which breaks paste handling entirely in affected environments. Add a safe fallback before .replace(...).

Proposed fix
-                    const text = (e.clipboardData || window.clipboardData)
-                        .getData('text')
-                        .replace(/\r\n/g, '\n')
-                        .replace(/\n+$/, '');
+                    var clipboard = e.clipboardData || window.clipboardData;
+                    var rawText =
+                        clipboard && typeof clipboard.getData === 'function'
+                            ? clipboard.getData('text') || clipboard.getData('Text') || ''
+                            : '';
+                    const text = String(rawText).replace(/\r\n/g, '\n').replace(/\n+$/, '');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const text = (e.clipboardData || window.clipboardData)
.getData('text')
.replace(/\r\n/g, '\n')
.replace(/\n+$/, '');
var clipboard = e.clipboardData || window.clipboardData;
var rawText =
clipboard && typeof clipboard.getData === 'function'
? clipboard.getData('text') || clipboard.getData('Text') || ''
: '';
const text = String(rawText).replace(/\r\n/g, '\n').replace(/\n+$/, '');
🤖 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/mck-sidebox-1.0.js` around lines 4366 - 4369, The current
assignment to text calls (e.clipboardData ||
window.clipboardData).getData('text') directly which can throw when clipboard
APIs are absent; change it to first capture the data source (e.clipboardData ||
window.clipboardData), check that it's truthy, call getData('text') only when
present, and then run the .replace(...) on a safe string (e.g., raw || '') so
that e.clipboardData/window.clipboardData and getData are guarded; update the
assignment where text is computed (the const text = ... line) to use this safe
pattern referencing e.clipboardData, window.clipboardData and getData.

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.

1 participant