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

Update Resource Forms to Enhance Validation #9062

Open
wants to merge 30 commits into
base: develop
Choose a base branch
from

Conversation

JavidSumra
Copy link
Contributor

@JavidSumra JavidSumra commented Nov 8, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation (if applicable).
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Enhanced input validation for requested_quantity and assigned_quantity fields to accept only numeric values with a minimum of 1.
    • Added required fields for title and reason in the resource form, ensuring all necessary information is provided before submission.
  • Bug Fixes

    • Improved error handling and validation logic for form submissions, ensuring accurate feedback for users.
  • Tests

    • Updated test cases to enhance functionality, specifically for selecting options in the resource status update process.

@JavidSumra JavidSumra requested a review from a team as a code owner November 8, 2024 14:52
Copy link

netlify bot commented Nov 8, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit d7e44c0
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/674ab9d1f14ca500083c0744
😎 Deploy Preview https://deploy-preview-9062--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

Walkthrough

The changes involve updates to several components related to resource management. The ResourceCreate component now includes a utility function for sanitizing numeric input, enforcing numeric constraints on the requested_quantity field. The ResourceDetailsUpdate component has enhanced validation logic and error handling, particularly for new required fields. Additionally, a Cypress test file has been modified to improve test coverage for resource updates. A new utility function, sanitizeNumberInput, has also been introduced to ensure only numeric values are accepted in input fields.

Changes

File Change Summary
src/components/Resource/ResourceCreate.tsx - Added sanitizeNumberInput utility function.
- Modified TextFormField for requested_quantity to enforce numeric input (type="number", min={1}).
- Updated onInput event to call sanitizeNumberInput.
- Set default value of requested_quantity to 1.
src/components/Resource/ResourceDetailsUpdate.tsx - Updated validation logic by replacing assigned_facility_type with assigned_facility_object.
- Added required fields title and reason with error messages.
- Enhanced form submission logic to check for valid form state.
cypress/e2e/resource_spec/ResourcesHomepage.cy.ts - Adjusted import statements and added functionality to select an option from assigned_facility_object in tests.
src/Utils/utils.ts - Introduced sanitizeNumberInput function to sanitize numeric input in forms.

Assessment against linked issues

Objective Addressed Explanation
Required Quantity should not accept negative values (9053)
Description field should be mandatory (9053) No changes were made to enforce description field validation.

Possibly related PRs

  • Design of List View layout in Resource Page #9096: The ResourceList component changes include the sanitizeNumberInput function, which is also referenced in the ResourceCreate component, indicating a shared utility for input sanitization across resource-related components.

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad

🐇 In the fields where bunnies play,
Numbers hop and dance all day.
With inputs clean and errors few,
Resource updates, fresh and new!
So let’s rejoice, for changes bright,
Our forms are now a pure delight! 🥕


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5a0b57f and d7e44c0.

📒 Files selected for processing (3)
  • src/Utils/utils.ts (1 hunks)
  • src/components/Resource/ResourceCreate.tsx (4 hunks)
  • src/components/Resource/ResourceDetailsUpdate.tsx (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/Utils/utils.ts
  • src/components/Resource/ResourceDetailsUpdate.tsx
  • src/components/Resource/ResourceCreate.tsx

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

🧹 Outside diff range and nitpick comments (4)
src/components/Form/FormFields/TextFormField.tsx (1)

Line range hint 32-69: Consider enhancing error handling for validation constraints.

The current implementation relies on browser-native validation for min/max constraints. To improve user experience, consider adding custom error messages and validation handling.

Suggestions:

  1. Integrate with the existing form validation system
  2. Add specific error messages for min/max violations
  3. Consider adding a validationMode prop to control when validation occurs (onChange, onBlur, onSubmit)
  4. Add aria-labels for accessibility when validation fails

Would you like me to provide a code example implementing these suggestions?

src/components/Resource/ResourceCreate.tsx (1)

Line range hint 1-394: Consider architectural improvements for better type safety and validation consistency.

While the overall implementation is solid, consider these improvements:

  1. Define a proper type for the form state instead of using any:
interface ResourceFormState {
  category: string;
  sub_category: number;
  approving_facility: { id: string } | null;
  assigned_facility: { id: string } | null;
  emergency: string;
  title: string;
  reason: string;
  refering_facility_contact_name: string;
  refering_facility_contact_number: string;
  required_quantity: number | null;
}
  1. Create a consistent validation pattern across all fields using a validation schema library like Yup or Zod.

Would you like me to provide a complete example of how to implement these improvements?

src/components/Resource/ResourceDetailsUpdate.tsx (2)

51-59: LGTM! Consider enhancing error messages for better user experience.

The required field validations are properly implemented, particularly for the title and description fields. The error messages are clear but could be more user-friendly.

Consider enhancing the error messages to be more descriptive:

  assigned_facility_object: {
-   errorText: "Please Select Facility Type",
+   errorText: "Please select a facility to assign this resource to",
  },
  title: {
-   errorText: "Title is required.",
+   errorText: "Please provide a title for this resource request",
  },

274-274: Consider adding maximum value constraints for quantity fields.

While the min={1} constraint prevents negative values as required, consider adding a reasonable maximum value to prevent unrealistic quantities.

  <TextFormField
    label="Required Quantity"
    name="requested_quantity"
    type="number"
    min={1}
+   max={9999}
    value={state.form.requested_quantity}
    onChange={handleChange}
  />

Also applies to: 283-283

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 66ef112 and 46ec289.

📒 Files selected for processing (3)
  • src/components/Form/FormFields/TextFormField.tsx (2 hunks)
  • src/components/Resource/ResourceCreate.tsx (1 hunks)
  • src/components/Resource/ResourceDetailsUpdate.tsx (8 hunks)
🔇 Additional comments (4)
src/components/Resource/ResourceCreate.tsx (1)

Line range hint 385-394: LGTM: Description field validation is properly implemented.

The Description field implementation meets the PR objectives with:

  • Required field validation
  • Error handling
  • Internationalized labels and error messages
src/components/Resource/ResourceDetailsUpdate.tsx (3)

110-118: LGTM! Robust validation logic implementation.

The enhanced validation logic properly handles both facility objects and string fields, with appropriate type-specific checks.


161-161: LGTM! More intuitive validation check.

The inverted validation logic (!validateForm()) improves code readability by focusing on the positive case (valid form) rather than the negative case.


295-300: LGTM! Required fields properly implemented.

The title and description fields are now properly marked as required, fulfilling the PR objectives. The implementation includes both frontend validation (required attribute) and backend validation (through validateForm).

Also applies to: 311-313

src/components/Form/FormFields/TextFormField.tsx Outdated Show resolved Hide resolved
src/components/Form/FormFields/TextFormField.tsx Outdated Show resolved Hide resolved
src/components/Resource/ResourceCreate.tsx Show resolved Hide resolved
Copy link
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: 0

🧹 Outside diff range and nitpick comments (1)
cypress/e2e/resource_spec/ResourcesHomepage.cy.ts (1)

Line range hint 32-45: Add test cases for new validation requirements.

The "Create a resource request" test should include additional test cases to verify the new validation requirements:

  1. Attempt to create a resource with negative quantity (should fail)
  2. Attempt to create a resource with empty description (should fail)

This ensures the new validation logic is properly tested.

Consider adding these test cases:

it("Should not allow negative quantity in resource request", () => {
  // ... setup code similar to existing create test ...
  facilityPage.fillResourceRequestDetails(
    "Test User",
    phone_number,
    "Dummy",
    "Test title",
    "-10", // negative quantity
    "Test description",
  );
  facilityPage.clickSubmitRequestButton();
  // Verify error message or validation feedback
  cy.get('[data-testid="quantity-error"]').should('be.visible')
    .and('contain', 'Quantity must be positive');
});

it("Should not allow empty description in resource request", () => {
  // ... setup code similar to existing create test ...
  facilityPage.fillResourceRequestDetails(
    "Test User",
    phone_number,
    "Dummy",
    "Test title",
    "10",
    "", // empty description
  );
  facilityPage.clickSubmitRequestButton();
  // Verify error message or validation feedback
  cy.get('[data-testid="description-error"]').should('be.visible')
    .and('contain', 'Description is required');
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 46ec289 and 41c1b1c.

📒 Files selected for processing (1)
  • cypress/e2e/resource_spec/ResourcesHomepage.cy.ts (2 hunks)
🔇 Additional comments (2)
cypress/e2e/resource_spec/ResourcesHomepage.cy.ts (2)

1-1: LGTM!

The import reordering is acceptable and doesn't impact functionality.


71-74: LGTM! Well-structured facility selection step.

The addition of facility selection using a custom command enhances the test coverage and follows Cypress best practices.

@nihal467
Copy link
Member

image

@JavidSumra
Copy link
Contributor Author

Have you updated the value or is it already present there?
cc @nihal467

@nihal467
Copy link
Member

@JavidSumra i updated the value

Copy link
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

🧹 Outside diff range and nitpick comments (5)
src/components/Resource/ResourceDetailsUpdate.tsx (4)

52-60: Consider improving error message clarity

While the addition of required fields for title and description is good, the error message for assigned_facility_object could be more specific.

Consider updating the error message to be more descriptive:

  assigned_facility_object: {
-   errorText: "Please Select Facility Type",
+   errorText: "Please select an assigned facility",
  },

111-119: Consider enhancing type safety

While the validation logic is improved, consider adding TypeScript interfaces for the facility objects to make the code more type-safe and maintainable.

Consider adding:

interface FacilityObject {
  name: string;
  id: string;
  // other relevant properties
}

// Then update the form interface
interface ResourceForm {
  approving_facility_object: FacilityObject | null;
  assigned_facility_object: FacilityObject | null;
  // other form fields
}

275-279: Consider additional quantity validation improvements

While the min attribute and handleNegativeValue prevent negative values, consider adding these improvements:

  1. Add max validation to prevent unreasonably large numbers
  2. Validate that assigned_quantity doesn't exceed requested_quantity

Consider updating both quantity fields:

  <TextFormField
    label="Required Quantity"
    name="requested_quantity"
    type="number"
    min={1}
+   max={999999}
    value={state.form.requested_quantity}
    onChange={handleChange}
    onInput={handleNegativeValue}
  />

  <TextFormField
    name="assigned_quantity"
    type="number"
    min={1}
+   max={state.form.requested_quantity}
    label="Approved Quantity"
    value={state.form.assigned_quantity}
    onChange={handleChange}
    disabled={state.form.status !== "PENDING"}
    onInput={handleNegativeValue}
  />

Also applies to: 285-291


298-303: Consider enhancing validation UX

The required attribute is correctly added to title and description fields. However, consider these UX improvements:

  1. Add visual indicators (like asterisks) for required fields
  2. Show validation messages immediately on field blur rather than only on form submission

Consider implementing a reusable required field label component:

const RequiredFieldLabel: React.FC<{label: string}> = ({label}) => (
  <span>
    {label} <span className="text-red-500">*</span>
  </span>
);

Then use it in your form fields:

  <TextFormField
    name="title"
    type="text"
-   label="Request Title"
+   label={<RequiredFieldLabel label="Request Title" />}
    // ... other props
  />

Also applies to: 314-316

src/Utils/utils.ts (1)

547-560: Consider moving form-specific utilities to a dedicated module

This function is specifically for form validation and is tightly coupled with React's form handling. Consider:

  1. Moving it to a dedicated form utilities module (e.g., src/Utils/formUtils.ts or src/components/common/forms/utils.ts)
  2. Grouping it with other form-related utilities for better organization
  3. Adding JSDoc documentation to explain its purpose and usage
🧰 Tools
🪛 Biome

[error] 557-557: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 41c1b1c and 098ba35.

📒 Files selected for processing (4)
  • src/Utils/utils.ts (1 hunks)
  • src/components/Form/FormFields/TextFormField.tsx (2 hunks)
  • src/components/Resource/ResourceCreate.tsx (2 hunks)
  • src/components/Resource/ResourceDetailsUpdate.tsx (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Form/FormFields/TextFormField.tsx
  • src/components/Resource/ResourceCreate.tsx
🧰 Additional context used
🪛 Biome
src/Utils/utils.ts

[error] 557-557: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (2)
src/components/Resource/ResourceDetailsUpdate.tsx (2)

28-28: LGTM: Good separation of concerns

The addition of the handleNegativeValue utility import aligns with the PR objective of preventing negative values and follows good practices by keeping validation logic in a separate utility file.


Line range hint 1-341: Verify the validation behavior in edge cases

The implementation successfully addresses the PR objectives. However, let's verify the validation behavior in these edge cases:

  1. Form submission with zero quantities
  2. Copy-paste of negative values
  3. Browser form validation bypass
✅ Verification successful

Input validation is properly implemented to prevent negative values

The implementation successfully addresses the validation requirements:

  1. The handleNegativeValue utility function in Utils/utils.ts effectively prevents negative values by:

    • Removing all instances of '-' from the input value
    • Ensuring the input is a valid number
    • Resetting to empty if invalid
  2. The form fields have proper validation:

    • Both quantity fields use min={1} for HTML5 validation
    • Both fields implement handleNegativeValue for copy-paste prevention
    • Required fields validation is implemented in validateForm()

The implementation provides multiple layers of validation and is consistent with other resource-related components in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other quantity validation implementations in the codebase
rg -l "handleNegativeValue|min={[1-9]" --type typescript

# Search for similar form validation patterns
ast-grep --pattern 'validateForm() {
  $$$
  return $_;
}'

Length of output: 257


Script:

#!/bin/bash
# Search for other quantity validation implementations in the codebase
rg -l "handleNegativeValue" --type typescript
rg -l 'min=\{1\}' --type typescript

# Search for similar form validation patterns
ast-grep --pattern 'validateForm = () => {
  $$$
}'

# Search for quantity validation in utils
rg -A 5 "handleNegativeValue" --type typescript

Length of output: 290


Script:

#!/bin/bash
# Search for other quantity validation implementations in the codebase
rg -l "handleNegativeValue"
rg -l 'min=\{1\}'

# Search for similar form validation patterns
ast-grep --pattern 'const handleNegativeValue = ($$$) => {
  $$$
}'

# Search for quantity validation in utils
rg -A 5 "handleNegativeValue"

Length of output: 2874


Script:

#!/bin/bash
# Check implementation of handleNegativeValue in utils
cat src/Utils/utils.ts

# Check form validation in ResourceCreate for consistency
rg -A 10 "validateForm" src/components/Resource/ResourceCreate.tsx

Length of output: 16354

src/Utils/utils.ts Outdated Show resolved Hide resolved
…-negative-quantity-and-empty-description' into issues/9053/prevent-negative-quantity-and-empty-description
Copy link
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 098ba35 and 7f5e000.

📒 Files selected for processing (1)
  • src/Utils/utils.ts (1 hunks)
🧰 Additional context used
🪛 Biome
src/Utils/utils.ts

[error] 553-553: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

src/Utils/utils.ts Outdated Show resolved Hide resolved
src/components/Form/FormFields/TextFormField.tsx Outdated Show resolved Hide resolved
src/components/Form/FormFields/TextFormField.tsx Outdated Show resolved Hide resolved
src/Utils/utils.ts Outdated Show resolved Hide resolved
src/Utils/utils.ts Outdated Show resolved Hide resolved
Copy link
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: 5

🧹 Outside diff range and nitpick comments (2)
src/components/Resource/ResourceCreate.tsx (1)

Line range hint 127-160: Add explicit validation for requested_quantity

The validateForm function should include explicit validation for requested_quantity to ensure server-side validation matches client-side constraints.

Add this case to the validateForm switch statement:

case "requested_quantity": {
  const quantity = Number(state.form[field]);
  if (!state.form[field] || isNaN(quantity) || quantity < 1) {
    errors[field] = requiredFields[field].invalidText;
    isInvalidForm = true;
  }
  return;
}
src/components/Resource/ResourceDetailsUpdate.tsx (1)

111-119: Consider consolidating facility object validation

The current validation for facility objects is repetitive. Consider extracting this logic into a helper function for better maintainability.

+const isFacilityValid = (facility: any) => facility && facility.name;
+
 if (
   field === "approving_facility_object" ||
   field === "assigned_facility_object"
 ) {
-  if (!state.form[field] || !state.form[field]?.name) {
+  if (!isFacilityValid(state.form[field])) {
     errors[field] = requiredFields[field].errorText;
     isInvalidForm = true;
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6440d4b and 5a0b57f.

📒 Files selected for processing (3)
  • src/Utils/utils.ts (1 hunks)
  • src/components/Resource/ResourceCreate.tsx (4 hunks)
  • src/components/Resource/ResourceDetailsUpdate.tsx (8 hunks)
🔇 Additional comments (4)
src/components/Resource/ResourceCreate.tsx (2)

303-307: LGTM! Input constraints are properly implemented

The implementation correctly prevents negative values through:

  1. type="number" for numeric input
  2. min={1} to prevent zero/negative values
  3. sanitizeNumberInput for additional validation

303-307: Verify edge cases for quantity and description validation

Both fields have validation, but let's ensure all paths are tested:

  1. Quantity validation
  2. Description validation

Also applies to: 312-322

✅ Verification successful

Validation implementation is comprehensive and properly handles edge cases

The code implements robust validation for both quantity and description fields:

  • Quantity validation:

    • HTML min={1} attribute prevents negative values
    • sanitizeNumberInput function removes non-numeric characters and enforces minimum value
    • Form-level validation through validateForm() before submission
  • Description/required fields validation:

    • Comprehensive validation through requiredFields object
    • Form-level validation before submission
    • Error handling for empty fields and invalid inputs
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for tests covering these validations

# Check for quantity validation tests
echo "Searching for quantity validation tests..."
rg -l "requested_quantity.*validation|quantity.*test" --type=typescript --type=javascript

# Check for description validation tests
echo "Searching for description validation tests..."
rg -l "reason.*required|description.*validation" --type=typescript --type=javascript

Length of output: 444


Script:

#!/bin/bash
# Let's try a different approach to search for test files and validation logic

# Search for test files related to ResourceCreate
echo "Searching for ResourceCreate test files..."
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts | grep -i "resource"

# Search for validation logic in ResourceCreate
echo "Searching for validation logic in ResourceCreate..."
rg "validation|sanitize|required" src/components/Resource/ResourceCreate.tsx

# Search for form state and validation patterns
echo "Searching for form state and validation patterns..."
ast-grep --pattern 'const $_ = useForm<$_>({
  $$$
})'

Length of output: 1181


Script:

#!/bin/bash
# Let's examine the validation implementation more closely

# Check the validation logic and required fields implementation
echo "Checking validation implementation..."
rg -A 10 "requiredFields.*=" src/components/Resource/ResourceCreate.tsx

# Look for form submission and error handling
echo "Checking form submission and error handling..."
rg -A 10 "handleSubmit" src/components/Resource/ResourceCreate.tsx

# Check sanitizeNumberInput implementation
echo "Checking number sanitization..."
rg -A 5 "sanitizeNumberInput.*=" src/Utils/utils.ts

Length of output: 1853

src/components/Resource/ResourceDetailsUpdate.tsx (2)

28-28: LGTM: Form validation setup aligns with requirements

The addition of validation requirements for title and description fields, along with the sanitizeNumberInput utility import, properly supports the PR objectives.

Also applies to: 52-60


275-278: LGTM: Form field implementations meet requirements

The implementation properly prevents negative values through:

  • min attribute set to 1
  • sanitizeNumberInput validation
  • server-side validation via default values

And ensures description is mandatory through:

  • required attribute
  • form validation
  • error message display

Also applies to: 285-290, 298-303, 314-316

src/components/Resource/ResourceCreate.tsx Show resolved Hide resolved
src/components/Resource/ResourceCreate.tsx Show resolved Hide resolved
src/Utils/utils.ts Outdated Show resolved Hide resolved
@JavidSumra
Copy link
Contributor Author

Hey @nihal467 can you please add needs-testing label on this PR?

@github-actions github-actions bot added needs-triage question Further information is requested labels Nov 27, 2024
@nihal467 nihal467 added needs testing and removed question Further information is requested test failed needs-triage labels Nov 28, 2024
@nihal467
Copy link
Member

image

  • when we create a new resource request, the approved quantity is having the same error mentioned before.

@JavidSumra before requesting a review, make sure the PR is working well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Resource Update Allows Negative Quantity and Empty Description Fields
3 participants