Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validation Fixes #649

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open

Conversation

belwalshubham
Copy link
Collaborator

@belwalshubham belwalshubham commented Dec 19, 2024

Summary by CodeRabbit

  • New Features

    • Updated validation logic for collection camp dates in the form.
    • Streamlined error messages to focus on relevant fields.
  • Bug Fixes

    • Removed unnecessary validation checks for institution dates.
  • Documentation

    • Clarified error messages to reflect current validation criteria.

Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

The pull request modifies the customValidateFields function in the afForm.component.js file, specifically focusing on validation logic for collection camp dates. The changes narrow the validation scope to only the afformCollectionCampIntentDetails form, removing previous checks for institution collection camp intent. The validation now concentrates on checking start and end dates for past or current dates and ensuring the end date is not before the start date.

Changes

File Change Summary
wp-content/plugins/civicrm/civicrm/ext/afform/core/ang/af/afForm.component.js Modified customValidateFields function to streamline date validation for collection camp dates

Suggested labels

status : ready for review

Suggested reviewers

  • tarunnjoshi

Poem

🗓️ Dates dance, validation's art
Trimming checks with surgical smart
Collection camps, now lean and clean
No more checks that fall between
Validation's path, now crystal clear! 🎯

Possibly related PRs


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

@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)
wp-content/plugins/civicrm/civicrm/ext/afform/core/ang/af/afForm.component.js (1)

338-371: Consider splitting validation logic into separate functions

The customValidateFields function has grown to handle multiple types of validations (email, phone, dates, postal code). This violates the Single Responsibility Principle and makes the code harder to maintain.

Consider refactoring into separate validation functions:

function validateEmail(element) {
  // Email validation logic
}

function validatePhone(element) {
  // Phone validation logic
}

function validateCollectionCampDates(element) {
  // Collection camp dates validation logic
}

function validatePostalCode(element) {
  // Postal code validation logic
}

function customValidateFields() {
  const validators = [
    validateEmail,
    validatePhone,
    validateCollectionCampDates,
    validatePostalCode
  ];
  
  const results = validators
    .map(validator => validator($element))
    .filter(result => !result.isValid);
    
  if (results.length > 0) {
    CRM.alert(results.map(r => r.message).join('\n'), ts("Form Error"));
    return false;
  }
  
  return true;
}

This approach would:

  1. Make the code more maintainable
  2. Make it easier to add new validations
  3. Make it easier to test individual validation rules
  4. Improve code reusability
🧰 Tools
🪛 Biome (1.9.4)

[error] 343-343: Shouldn't redeclare 'today'. Consider to delete it or rename it.

'today' is defined here:

(lint/suspicious/noRedeclare)


[error] 350-350: Shouldn't redeclare 'errorMessage'. Consider to delete it or rename it.

'errorMessage' is defined here:

(lint/suspicious/noRedeclare)


[error] 351-351: Shouldn't redeclare 'isValid'. Consider to delete it or rename it.

'isValid' is defined here:

(lint/suspicious/noRedeclare)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a66563 and 63985a5.

📒 Files selected for processing (1)
  • wp-content/plugins/civicrm/civicrm/ext/afform/core/ang/af/afForm.component.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
wp-content/plugins/civicrm/civicrm/ext/afform/core/ang/af/afForm.component.js

[error] 343-343: Shouldn't redeclare 'today'. Consider to delete it or rename it.

'today' is defined here:

(lint/suspicious/noRedeclare)


[error] 350-350: Shouldn't redeclare 'errorMessage'. Consider to delete it or rename it.

'errorMessage' is defined here:

(lint/suspicious/noRedeclare)


[error] 351-351: Shouldn't redeclare 'isValid'. Consider to delete it or rename it.

'isValid' is defined here:

(lint/suspicious/noRedeclare)

Comment on lines +338 to +371
if (ctrl.getFormMeta().name === 'afformCollectionCampIntentDetails') {
var startDateValue = $element.find("af-field[name='Collection_Camp_Intent_Details.Start_Date'] .crm-form-date-wrapper input.crm-form-date").val();
var endDateValue = $element.find("af-field[name='Collection_Camp_Intent_Details.End_Date'] .crm-form-date-wrapper input.crm-form-date").val();

var institutionStartDateValue = $element.find("af-field[name='Institution_Collection_Camp_Intent.Collections_will_start_on_Date_'] .crm-form-date-wrapper input.crm-form-date").val();
var institutionEndDateValue = $element.find("af-field[name='Institution_Collection_Camp_Intent.Collections_will_end_on_Date_'] .crm-form-date-wrapper input.crm-form-date").val();

if ((startDateValue && endDateValue) || (institutionStartDateValue && institutionEndDateValue)) {

if (startDateValue && endDateValue) {
var today = new Date();
today.setHours(0, 0, 0, 0);

var startDateParts = startDateValue ? startDateValue.split('/') : institutionStartDateValue.split('/');
var endDateParts = endDateValue ? endDateValue.split('/') : institutionEndDateValue.split('/');

var startDateParts = startDateValue.split('/');
var endDateParts = endDateValue.split('/');
var startDate = new Date(startDateParts[2], startDateParts[1] - 1, startDateParts[0]);
var endDate = new Date(endDateParts[2], endDateParts[1] - 1, endDateParts[0]);

var errorMessage = '';
var isValid = true;

// Check if the start date is in the past or today
if (startDate <= today) {
errorMessage += `Collections cannot start (${startDateValue || institutionStartDateValue}) today or in the past.\n`;
errorMessage += `Collections cannot start (${startDateValue}) today or in the past.\n`;
isValid = false;
}

// Check if the end date is in the past, today
if (endDate <= today) {
errorMessage += `Collections cannot end (${endDateValue || institutionEndDateValue}) today or in the past.\n`;
errorMessage += `Collections cannot end ( ${endDateValue}) today or in the past.\n`;
isValid = false;

}

// Check if End Date is before Start Date
if (endDate < startDate) {
errorMessage += `Collections cannot end (${endDateValue || institutionEndDateValue}) before start (${startDateValue || institutionStartDateValue}).\n`;
errorMessage += `Collections cannot end (${endDateValue}) before start (${startDateValue}).\n`;
isValid = false;
}
}
}

}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor validation logic to improve maintainability and reduce duplication

The collection camp date validation logic has several issues that should be addressed:

  1. Variable redeclarations
  2. Repeated date parsing logic
  3. Hard-coded DOM selectors
  4. No input sanitization

Here's a suggested refactor:

- if (ctrl.getFormMeta().name === 'afformCollectionCampIntentDetails') {
-   var startDateValue = $element.find("af-field[name='Collection_Camp_Intent_Details.Start_Date'] .crm-form-date-wrapper input.crm-form-date").val();
-   var endDateValue = $element.find("af-field[name='Collection_Camp_Intent_Details.End_Date'] .crm-form-date-wrapper input.crm-form-date").val();
-   
-   if (startDateValue && endDateValue) {
-     var today = new Date();
-     today.setHours(0, 0, 0, 0); 
-     var startDateParts = startDateValue.split('/');
-     var endDateParts = endDateValue.split('/');
-     var startDate = new Date(startDateParts[2], startDateParts[1] - 1, startDateParts[0]);
-     var endDate = new Date(endDateParts[2], endDateParts[1] - 1, endDateParts[0]);
-
-     var errorMessage = '';
-     var isValid = true;
+ if (ctrl.getFormMeta().name === 'afformCollectionCampIntentDetails') {
+   const SELECTORS = {
+     startDate: "af-field[name='Collection_Camp_Intent_Details.Start_Date'] .crm-form-date-wrapper input.crm-form-date",
+     endDate: "af-field[name='Collection_Camp_Intent_Details.End_Date'] .crm-form-date-wrapper input.crm-form-date"
+   };
+   
+   const parseDate = (dateStr) => {
+     if (!dateStr || !/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateStr)) return null;
+     const [day, month, year] = dateStr.split('/');
+     return new Date(year, month - 1, day);
+   };
+   
+   const startDateValue = $element.find(SELECTORS.startDate).val();
+   const endDateValue = $element.find(SELECTORS.endDate).val();
+   
+   if (startDateValue && endDateValue) {
+     const today = new Date();
+     today.setHours(0, 0, 0, 0);
+     
+     const startDate = parseDate(startDateValue);
+     const endDate = parseDate(endDateValue);
+     
+     if (!startDate || !endDate) {
+       return {
+         isValid: false,
+         message: 'Invalid date format. Please use DD/MM/YYYY format.'
+       };
+     }

-     // Check if the start date is in the past or today
-     if (startDate <= today) {
-       errorMessage += `Collections cannot start (${startDateValue}) today or in the past.\n`;
-       isValid = false;
-     }
-
-     // Check if the end date is in the past, today
-     if (endDate <= today) {
-       errorMessage += `Collections cannot end ( ${endDateValue}) today or in the past.\n`;
-       isValid = false;
-     }
-
-     // Check if End Date is before Start Date
-     if (endDate < startDate) {
-       errorMessage += `Collections cannot end (${endDateValue}) before start (${startDateValue}).\n`;
-       isValid = false;
-     }
+     const validations = [
+       {
+         condition: startDate <= today,
+         message: `Collection start date (${startDateValue}) must be in the future.`
+       },
+       {
+         condition: endDate <= today,
+         message: `Collection end date (${endDateValue}) must be in the future.`
+       },
+       {
+         condition: endDate < startDate,
+         message: `Collection end date (${endDateValue}) cannot be before start date (${startDateValue}).`
+       }
+     ];
+     
+     const failures = validations.filter(v => v.condition);
+     return {
+       isValid: failures.length === 0,
+       message: failures.map(f => f.message).join('\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
if (ctrl.getFormMeta().name === 'afformCollectionCampIntentDetails') {
var startDateValue = $element.find("af-field[name='Collection_Camp_Intent_Details.Start_Date'] .crm-form-date-wrapper input.crm-form-date").val();
var endDateValue = $element.find("af-field[name='Collection_Camp_Intent_Details.End_Date'] .crm-form-date-wrapper input.crm-form-date").val();
var institutionStartDateValue = $element.find("af-field[name='Institution_Collection_Camp_Intent.Collections_will_start_on_Date_'] .crm-form-date-wrapper input.crm-form-date").val();
var institutionEndDateValue = $element.find("af-field[name='Institution_Collection_Camp_Intent.Collections_will_end_on_Date_'] .crm-form-date-wrapper input.crm-form-date").val();
if ((startDateValue && endDateValue) || (institutionStartDateValue && institutionEndDateValue)) {
if (startDateValue && endDateValue) {
var today = new Date();
today.setHours(0, 0, 0, 0);
var startDateParts = startDateValue ? startDateValue.split('/') : institutionStartDateValue.split('/');
var endDateParts = endDateValue ? endDateValue.split('/') : institutionEndDateValue.split('/');
var startDateParts = startDateValue.split('/');
var endDateParts = endDateValue.split('/');
var startDate = new Date(startDateParts[2], startDateParts[1] - 1, startDateParts[0]);
var endDate = new Date(endDateParts[2], endDateParts[1] - 1, endDateParts[0]);
var errorMessage = '';
var isValid = true;
// Check if the start date is in the past or today
if (startDate <= today) {
errorMessage += `Collections cannot start (${startDateValue || institutionStartDateValue}) today or in the past.\n`;
errorMessage += `Collections cannot start (${startDateValue}) today or in the past.\n`;
isValid = false;
}
// Check if the end date is in the past, today
if (endDate <= today) {
errorMessage += `Collections cannot end (${endDateValue || institutionEndDateValue}) today or in the past.\n`;
errorMessage += `Collections cannot end ( ${endDateValue}) today or in the past.\n`;
isValid = false;
}
// Check if End Date is before Start Date
if (endDate < startDate) {
errorMessage += `Collections cannot end (${endDateValue || institutionEndDateValue}) before start (${startDateValue || institutionStartDateValue}).\n`;
errorMessage += `Collections cannot end (${endDateValue}) before start (${startDateValue}).\n`;
isValid = false;
}
}
}
}
if (ctrl.getFormMeta().name === 'afformCollectionCampIntentDetails') {
const SELECTORS = {
startDate: "af-field[name='Collection_Camp_Intent_Details.Start_Date'] .crm-form-date-wrapper input.crm-form-date",
endDate: "af-field[name='Collection_Camp_Intent_Details.End_Date'] .crm-form-date-wrapper input.crm-form-date"
};
const parseDate = (dateStr) => {
if (!dateStr || !/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateStr)) return null;
const [day, month, year] = dateStr.split('/');
return new Date(year, month - 1, day);
};
const startDateValue = $element.find(SELECTORS.startDate).val();
const endDateValue = $element.find(SELECTORS.endDate).val();
if (startDateValue && endDateValue) {
const today = new Date();
today.setHours(0, 0, 0, 0);
const startDate = parseDate(startDateValue);
const endDate = parseDate(endDateValue);
if (!startDate || !endDate) {
return {
isValid: false,
message: 'Invalid date format. Please use DD/MM/YYYY format.'
};
}
const validations = [
{
condition: startDate <= today,
message: `Collection start date (${startDateValue}) must be in the future.`
},
{
condition: endDate <= today,
message: `Collection end date (${endDateValue}) must be in the future.`
},
{
condition: endDate < startDate,
message: `Collection end date (${endDateValue}) cannot be before start date (${startDateValue}).`
}
];
const failures = validations.filter(v => v.condition);
return {
isValid: failures.length === 0,
message: failures.map(f => f.message).join('\n')
};
}
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 343-343: Shouldn't redeclare 'today'. Consider to delete it or rename it.

'today' is defined here:

(lint/suspicious/noRedeclare)


[error] 350-350: Shouldn't redeclare 'errorMessage'. Consider to delete it or rename it.

'errorMessage' is defined here:

(lint/suspicious/noRedeclare)


[error] 351-351: Shouldn't redeclare 'isValid'. Consider to delete it or rename it.

'isValid' is defined here:

(lint/suspicious/noRedeclare)

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