Skip to content

Add validation for phone number and PAN card on contribution form#446

Closed
tarunnjoshi wants to merge 1 commit intodevelopfrom
add-validation-for-contribution-page
Closed

Add validation for phone number and PAN card on contribution form#446
tarunnjoshi wants to merge 1 commit intodevelopfrom
add-validation-for-contribution-page

Conversation

@tarunnjoshi
Copy link
Copy Markdown
Member

@tarunnjoshi tarunnjoshi commented Nov 13, 2024

Add validation for phone number and PAN card on the contribution form

Summary by CodeRabbit

  • New Features

    • Introduced validation for phone numbers and PAN card numbers on the contribution form.
    • Alerts users of invalid input and focuses on erroneous fields during form submission.
  • Improvements

    • Enhanced readability of message handling logic with consistent formatting.
    • Retained and improved the timeout mechanism for resetting the form.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes in main.js focus on improving the logic for message handling based on URL parameters and implementing validation for form inputs. Enhancements include consistent code formatting for better readability, the addition of regex-based validation for phone numbers and PAN card numbers, and the retention of the existing timeout mechanism for form resets. Alerts are triggered for invalid inputs, ensuring users are informed of errors. Overall, the modifications enhance input validation and the clarity of message handling without altering any exported or public entity declarations.

Changes

File Path Change Summary
wp-content/themes/goonj-crm/main.js Restructured message handling logic; added input validation for phone and PAN card numbers; improved code readability with consistent indentation and formatting; retained timeout mechanism for form reset with additional checks.

Possibly related PRs

  • Change mmt to frontend #274: Changes in main.js enhance message handling and form validation, which may relate to the overall user experience improvements also targeted in this PR.
  • Added additional params to auto fill form fields #384: The modifications in main.js for form handling and validation could be relevant to the enhancements made in the auto-fill functionality for form fields in this PR.
  • UI fixes for Donation page #425: The UI fixes for the Donation page may connect with the changes in main.js that improve form input handling and user feedback.
  • Add Monetary Contribution Tabs #441: The addition of new tabs for monetary contributions could relate to the overall enhancements in user interaction and form handling in main.js.
  • Fix the Monitary Feedbacks #442: The changes in main.js regarding user feedback and validation may align with the fixes for monetary feedbacks addressed in this PR.

Suggested labels

status : ready for review

Suggested reviewers

  • pokhiii

🎉 In the land of code where functions play,
A validation dance brightens the day.
With regex rules and messages clear,
Input errors now vanish, oh dear!
Readable lines, structured and neat,
A joyful commit, oh what a treat! 🎊


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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
Copy Markdown

@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: 2

🧹 Outside diff range and nitpick comments (2)
wp-content/themes/goonj-crm/main.js (2)

Line range hint 6-46: Refactor message handling to reduce duplication and improve maintainability

The current implementation contains repeated HTML templates and styling. Consider refactoring to:

  1. Extract messages into a configuration object
  2. Create a reusable template rendering function
  3. Consolidate common styles

Here's a suggested improvement:

const MESSAGE_TEMPLATES = {
  'not-inducted-volunteer': {
    title: 'You are not registered as a volunteer with us.',
    message: 'To set up a collection camp, please take a moment to fill out the volunteer registration form below.'
  },
  'dropping-center': {
    title: 'You are not registered as a volunteer with us.',
    message: 'To set up a dropping center, please take a moment to fill out the volunteer registration form below.'
  },
  // ... other messages
};

function renderMessage(type) {
  const template = MESSAGE_TEMPLATES[type];
  return `
    <div class="w-520 mt-30">
      <p class="fw-600 font-sans fz-20 mb-6">${template.title}</p>
      <p class="fw-400 font-sans fz-16 mt-0 mb-24">${template.message}</p>
    </div>
  `;
}

71-82: Consider adding more robust validation patterns

The current regex patterns might be too strict:

  • Phone number pattern doesn't account for country codes or different formats
  • PAN card validation is case-sensitive

Consider updating the validation patterns:

const fields = [
  {
    labelText: "Mobile Number",
    regex: /^(\+\d{1,3}[- ]?)?\d{10}$/,
    errorMessage: "Please enter a valid mobile number. Include country code if applicable.",
  },
  {
    labelText: "Enter PAN Card Number",
    regex: /^[A-Za-z]{5}[0-9]{4}[A-Za-z]$/i,
    errorMessage: "Please enter a valid PAN card number (e.g., ABCDE1234F).",
  }
];
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c3f4623 and d1d8b62.

📒 Files selected for processing (1)
  • wp-content/themes/goonj-crm/main.js (2 hunks)
🔇 Additional comments (1)
wp-content/themes/goonj-crm/main.js (1)

67-106: Ensure server-side validation is implemented

While client-side validation improves user experience, it can be bypassed. Ensure that robust server-side validation is also implemented for these fields to maintain data integrity and security.

Comment on lines +53 to +64
setTimeout(function () {
var resetButton = document.querySelector('button[type="reset"]');

if (resetButton) {
resetButton.addEventListener("click", function (event) {
event.preventDefault();

// Refresh the page to reset all fields
location.reload(true);
});
}
}, 1000);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace page reload with proper form reset implementation

The current implementation uses a page reload as a temporary solution, which is inefficient and provides a poor user experience.

Consider implementing a proper form reset:

document.addEventListener("DOMContentLoaded", function () {
  const form = document.querySelector('form');
  const resetButton = form?.querySelector('button[type="reset"]');
  
  if (resetButton && form) {
    resetButton.addEventListener("click", function (event) {
      event.preventDefault();
      form.reset();
      // Reset any custom form state here
      const inputs = form.querySelectorAll('input, select, textarea');
      inputs.forEach(input => input.classList.remove('error', 'valid'));
    });
  }
});

Also, the setTimeout seems unnecessary. Consider removing it unless there's a specific reason for the delay.

Comment on lines +84 to +106
fields.forEach(field => {
// Select the label by labelText and find the associated input
const label = Array.from(document.querySelectorAll("label")).find(el => el.textContent.includes(field.labelText));
if (label) {
const input = document.querySelector(`input[name="${label.getAttribute("for")}"]`);

if (resetButton) {
resetButton.addEventListener("click", function (event) {
event.preventDefault();
if (input) {
const form = input.closest("form");

// Refresh the page to reset all fields
location.reload(true);
});
}
}, 1000);
// Attach validation on form submission
if (form) {
form.addEventListener("submit", function (event) {
const value = input.value;
if (!field.regex.test(value)) {
event.preventDefault();
alert(field.errorMessage);
input.focus();
}
});
}
}
}
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve form validation UX and error handling

Current implementation has several areas for improvement:

  1. Relies on label text for field identification (brittle)
  2. Uses alert() for error messages (poor UX)
  3. No real-time validation
  4. No visual feedback on input fields

Consider implementing:

document.addEventListener("DOMContentLoaded", function () {
  const form = document.querySelector('form');
  
  fields.forEach(field => {
    const input = form?.querySelector(`[data-validation="${field.type}"]`);
    if (!input) return;

    // Add error container
    const errorSpan = document.createElement('span');
    errorSpan.className = 'error-message';
    input.parentNode.appendChild(errorSpan);

    // Real-time validation
    input.addEventListener('input', validateField);
    
    function validateField() {
      const isValid = field.regex.test(input.value);
      input.classList.toggle('error', !isValid);
      input.classList.toggle('valid', isValid);
      errorSpan.textContent = isValid ? '' : field.errorMessage;
    }
  });

  form?.addEventListener('submit', function(event) {
    const hasErrors = fields.some(field => {
      const input = form.querySelector(`[data-validation="${field.type}"]`);
      return input && !field.regex.test(input.value);
    });
    
    if (hasErrors) {
      event.preventDefault();
    }
  });
});

Also add corresponding CSS:

.error { border-color: red; }
.valid { border-color: green; }
.error-message {
  color: red;
  font-size: 12px;
  display: block;
  margin-top: 5px;
}

@tarunnjoshi
Copy link
Copy Markdown
Member Author

Close as not needed

@pokhiii pokhiii deleted the add-validation-for-contribution-page branch April 19, 2025 11:29
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