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

Added Validations to Valueset form Name and Slug fields along with translations for error messages. #10838

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

Conversation

hrit2773
Copy link
Contributor

@hrit2773 hrit2773 commented Feb 27, 2025

Proposed Changes

image

@rithviknishad @Jacobjeevan

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • 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

Summary by CodeRabbit

  • New Features

    • Improved form validation for slug inputs, ensuring entries meet specified character content and length constraints.
    • Added clear user feedback messages detailing acceptable slug formats and warnings for excessive length.
    • Enhanced input processing by automatically trimming whitespace from relevant form fields.
  • Bug Fixes

    • Removed unnecessary navigation functionality, streamlining the form submission process.

@hrit2773 hrit2773 requested a review from a team as a code owner February 27, 2025 06:13
Copy link
Contributor

coderabbitai bot commented Feb 27, 2025

Walkthrough

This pull request introduces enhancements to slug validation and messaging. A new entry for slug validation is added in the JSON locale file. Additionally, the validation schema in the ValueSetForm has been updated: both the name and slug fields now trim whitespace, while the slug field enforces minimum (5) and maximum (25) length requirements and a regex pattern constraint. The overall structure remains intact, but the validations have been improved for better input handling.

Changes

File(s) Change Summary
public/locale/en.json Added "slug_format_message": "Slug must only contain letters, numbers, underscores, and hyphens" for slug validation.
src/components/ValueSet/ValueSetForm.tsx Updated valuesetFormSchema to trim name and slug; added minimum (5) and maximum (25) length rules and regex format for slug. Removed a blank line after schema definition.

Possibly related PRs

  • Fixed Name and Slug field validations in Valueset form #10805: The changes in the main PR regarding the addition of a validation message for the "slug" functionality are directly related to the modifications in the retrieved PR that enhance the validation rules for the same "slug" field in the ValueSetForm.tsx file.

Suggested labels

needs review, tested, good to merge

Suggested reviewers

  • Jacobjeevan
  • rithviknishad

Poem

I'm a little bunny, hopping through the code,
With slugs now tamed on a validated road.
Trimming here, checking there, message bright and clear,
Each little change brings a cheer near.
Hop along, dear coder, and enjoy this joyful load! 🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 44b09b1 and 2a7f6c5.

📒 Files selected for processing (2)
  • public/locale/en.json (1 hunks)
  • src/components/ValueSet/ValueSetForm.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • public/locale/en.json
  • src/components/ValueSet/ValueSetForm.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)

🪧 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 generate docstrings to generate docstrings for this 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

netlify bot commented Feb 27, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 2a7f6c5
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67c983b53cc36e0008fdbb86
😎 Deploy Preview https://deploy-preview-10838.preview.ohc.network
📱 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 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
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b40c931 and 9477d9e.

📒 Files selected for processing (2)
  • public/locale/en.json (1 hunks)
  • src/components/ValueSet/ValueSetForm.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: Header rules - care-ohc
  • GitHub Check: Pages changed - care-ohc
  • GitHub Check: Test
  • GitHub Check: CodeQL-Build
  • GitHub Check: lint
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)
🔇 Additional comments (2)
public/locale/en.json (1)

2216-2217: New validation messages added for slug field.

Good addition of translation messages for the slug validation. These will provide clear feedback to users when entering invalid or too lengthy slugs.

src/components/ValueSet/ValueSetForm.tsx (1)

350-352: Good improvement with string trimming.

Adding .trim() to the name field validation is a good practice to prevent whitespace-only inputs or accidental leading/trailing spaces.

Comment on lines 352 to 359
slug: z
.string()
.trim()
.min(5, t("field_required"))
.max(25, t("slug_lengthy_message"))
.regex(/^[-\w]+$/, {
message: t("slug_format_message"),
}),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Error message key mismatch in slug validation.

There's a mismatch between the translation key used here (slug_lengthy_message) and the actual key defined in en.json (slug_lengthy). This will cause the error message to not display correctly.

-      .max(25, t("slug_lengthy_message"))
+      .max(25, t("slug_lengthy"))

The additional validation requirements for the slug field (min length, max length, and regex pattern) are well implemented and will help ensure consistent slug formats.

📝 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
slug: z
.string()
.trim()
.min(5, t("field_required"))
.max(25, t("slug_lengthy_message"))
.regex(/^[-\w]+$/, {
message: t("slug_format_message"),
}),
slug: z
.string()
.trim()
.min(5, t("field_required"))
.max(25, t("slug_lengthy"))
.regex(/^[-\w]+$/, {
message: t("slug_format_message"),
}),

@hrit2773
Copy link
Contributor Author

@Jacobjeevan @rithviknishad can you review this again I have added translations as suggested by @Jacobjeevan

export function ValueSetForm({
initialData,
onSubmit,
isSubmitting,
}: ValueSetFormProps) {
const { t } = useTranslation();

const valuesetFormSchema = z.object({
Copy link
Contributor

Choose a reason for hiding this comment

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

You can import t function directly:

import { t } from "i18next"

This allows to keep the schema outside as before.

@hrit2773
Copy link
Contributor Author

@Jacobjeevan I have tried that first but the associated translation was not being displayed. It was displaying field_required. It was not fetching the translation. I have checked it that is the reason why I changed like that

@github-actions github-actions bot added needs-triage question Further information is requested labels Feb 27, 2025
@AdityaJ2305
Copy link
Contributor

@hrit2773 , refresh the page then check

@hrit2773
Copy link
Contributor Author

@AdityaJ2305 yes I checked that. Surprisingly when I removed trim function the error translations are showing correctly but when I added trim its not

@AdityaJ2305
Copy link
Contributor

@AdityaJ2305 yes I checked that. Surprisingly when I removed trim function the error translations are showing correctly but when I added trim its not

I'm saying about the translation key is it fixed after refresh ?

@hrit2773
Copy link
Contributor Author

@AdityaJ2305 no its not displaying

@AdityaJ2305
Copy link
Contributor

Screenshot 2025-02-27 at 3 55 00 PM

working fine on my side

@hrit2773
Copy link
Contributor Author

@AdityaJ2305 Ohh really.. let me try once again

@hrit2773
Copy link
Contributor Author

@Jacobjeevan can you check it now

@Jacobjeevan Jacobjeevan added needs testing and removed question Further information is requested changes required needs-triage labels Feb 28, 2025
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

🧹 Nitpick comments (1)
src/components/ValueSet/ValueSetForm.tsx (1)

4-4: Consider consolidating translation approaches

The code currently uses two different approaches to access translations:

  1. Importing t directly (line 4) for use in the schema
  2. Using useTranslation() hook inside the component (line 410)

While this works, it's better to use a consistent approach. Consider one of these options:

Option 1: Define the schema inside the component to use the same t instance:

-const valuesetFormSchema = z.object({...});

export function ValueSetForm({
  initialData,
  onSubmit,
  isSubmitting,
}: ValueSetFormProps) {
  const { t } = useTranslation();
+  
+  const valuesetFormSchema = z.object({
+    name: z.string().trim().min(1, t("field_required")),
+    slug: z
+      .string()
+      .trim()
+      .min(5, t("field_required"))
+      .max(25, t("slug_lengthy_message"))
+      .regex(/^[-\w]+$/, {
+        message: t("slug_format_message"),
+      }),
+    // rest of the schema...
+  });

Option 2: Use a factory function to create the schema with the translation function:

-const valuesetFormSchema = z.object({...});
+const createValuesetFormSchema = (t: any) => z.object({
+  name: z.string().trim().min(1, t("field_required")),
+  slug: z
+    .string()
+    .trim()
+    .min(5, t("field_required"))
+    .max(25, t("slug_lengthy_message"))
+    .regex(/^[-\w]+$/, {
+      message: t("slug_format_message"),
+    }),
+  // rest of the schema...
+});

export function ValueSetForm({
  initialData,
  onSubmit,
  isSubmitting,
}: ValueSetFormProps) {
  const { t } = useTranslation();
+  const valuesetFormSchema = createValuesetFormSchema(t);

Also applies to: 410-410

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2e1d86b and fec1b70.

📒 Files selected for processing (1)
  • src/components/ValueSet/ValueSetForm.tsx (2 hunks)
🔇 Additional comments (3)
src/components/ValueSet/ValueSetForm.tsx (3)

344-353: Improved validation for name and slug fields

The enhanced validation for name and slug fields with trimming whitespace and regex pattern validation is a good addition that will ensure consistent data format. The regex pattern /^[-\w]+$/ correctly enforces that slugs only contain letters, numbers, underscores, and hyphens.


350-351:

✅ Verification successful

Verify translation key consistency

Make sure the translation key slug_lengthy_message is properly defined in your locale files to match what you're using in the code.


🏁 Script executed:

#!/bin/bash
# Check if the translation key exists in locale files
grep -r "slug_lengthy_message" public/locale/

Length of output: 116


Translation key 'slug_lengthy_message' is properly defined in the locale files.
The verification confirmed that the key exists in public/locale/en.json with the appropriate value ("Slug is too lengthy"). No changes are necessary.


347-353:

❓ Verification inconclusive

Verify the translation implementation

Based on the PR comments, there were issues with translations not displaying correctly. Ensure that the translations are working as expected when the form validation is triggered.


🌐 Web query:

What are best practices for handling translations in React form validation messages?

💡 Result:

When handling translations in React form validation messages, follow these best practices to ensure a seamless multilingual experience:

1. Use Internationalization Libraries

Integrate robust i18n libraries like react-i18next or FormatJS (react-intl)[3] to manage translation keys and locale switching efficiently. These tools provide:

  • Centralized translation files (e.g., JSON)
  • Dynamic message interpolation
  • Pluralization and formatting support

2. Decouple Validation Messages from Logic

Store all validation messages as translation keys instead of hardcoding strings:

// en.json
{
  "validation.required": "This field is required",
  "validation.email": "Invalid email format"
}

3. Integrate with Validation Libraries

For Yup (commonly used with Formik):

const schema = Yup.object().shape({
  email: Yup.string()
    .email(t('validation.email'))
    .required(t('validation.required'))
});

Listen to language changes and force revalidation:

i18n.on('languageChanged', () => {
  Object.keys(formik.errors).forEach(fieldName => {
    formik.setFieldTouched(fieldName);
  });
});

Source[2]

For React Hook Form:

const { t } = useTranslation();
const schema = yup.object().shape({
  password: yup.string()
    .min(8, t('validation.password.min'))
});

useForm({
  resolver: yupResolver(schema)
});

4. Handle Dynamic Language Changes

Use hooks or HOCs to sync form errors with active locale:

const useTranslateFormErrors = (form) => {
  const { t } = useTranslation();

  useEffect(() => {
    Object.keys(form.errors).forEach(field => {
      form.setFieldError(field, t(form.errors[field]));
    });
  }, [i18n.language]);
};

Source[2]

5. Consider Validation Library Support

Some libraries like Fonk provide built-in i18n integration:

Validators.required.setErrorMessage(t('required'));

Source[5]

6. Implement Accessible Error Display

Combine translation with ARIA live regions:

<Formik>
  {({ errors }) => (
    <div role="alert" aria-live="polite">
      {t(errors.email)}
    </div>
  )}
</Formik>

Comparison Table: Approach Strategies

Method Pros Cons
Yup + Formik Tight integration Manual language change handling
React Hook Form Uncontrolled performance Requires custom resolvers
Native Constraints Browser-native Limited customization

Key Recommendations

  • Use memoized validation schemas to prevent unnecessary recalculations
  • Centralize all form copy in translation files
  • Test edge cases like right-to-left languages
  • Combine client-side + server-side validation messages

By following these patterns, you'll create forms that smoothly adapt to locale changes while maintaining clean code structure[4][7][9].

Citations:


Verify Translation Implementation

The current use of the t function within the Yup validation schema aligns with best practices for using translation keys in form validations. However, please verify the following to ensure translations display correctly when validation is triggered:

  • Confirm that the translation keys ("field_required", "slug_lengthy_message", "slug_format_message") are correctly defined in your localization files.
  • If the form supports dynamic language switching, ensure that the validation schema is recreated or that error messages are refreshed when the active language changes.
  • Double-check that the i18n library (e.g., react-i18next) is properly configured and that translations are correctly injected at runtime.

@hrit2773 hrit2773 requested a review from Jacobjeevan February 28, 2025 09:29
.string()
.trim()
.min(5, t("field_required"))
.max(25, t("slug_lengthy_message"))
Copy link
Member

Choose a reason for hiding this comment

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

let's use variables to keep the message generic so that it can be re-used elsewhere instead of creating too many translations keys specific for each one

Suggested change
.max(25, t("slug_lengthy_message"))
.max(25, t("max_character_validation", { length: 25 }))

Copy link
Contributor

Choose a reason for hiding this comment

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

Complete the merge checklist as well @hrit2773

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Complete the merge checklist as well @hrit2773

Yup

@hrit2773
Copy link
Contributor Author

hrit2773 commented Mar 4, 2025

@rithviknishad @Jacobjeevan made the suggested change

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Mar 4, 2025
Copy link

github-actions bot commented Mar 4, 2025

Conflicts have been detected against the base branch. Please merge the base branch into your branch.
cc: @hrit2773

See: https://docs.ohc.network/docs/contributing#how-to-resolve-merge-conflicts

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

🔭 Outside diff range comments (1)
src/components/ValueSet/ValueSetForm.tsx (1)

499-515: ⚠️ Potential issue

Fix undefined goBack function error

The goBack function is referenced in the Cancel button's click handler but is not defined, causing a TypeScript error. According to the AI summary, the goBack functionality was intended to be removed.

You have two options to fix this issue:

Option 1: Import and use the useNavigate hook (recommended):

- onClick={() => goBack("/admin/valuesets")}
+ onClick={() => navigate("/admin/valuesets")}

With the corresponding import at the top:

import { useNavigate } from "react-router-dom";

And adding this inside the component:

const navigate = useNavigate();

Option 2: If you want to completely remove the Cancel button functionality as mentioned in the summary:

- <Button
-   variant="outline"
-   disabled={isSubmitting}
-   type="button"
-   onClick={() => goBack("/admin/valuesets")}
- >
-   {t("cancel")}
- </Button>
🧰 Tools
🪛 GitHub Check: cypress-run (1)

[failure] 504-504:
Cannot find name 'goBack'.

🪛 GitHub Actions: Cypress Tests

[error] 504-504: TS2304: Cannot find name 'goBack'.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 861fc8e and c828fcd.

📒 Files selected for processing (2)
  • public/locale/en.json (1 hunks)
  • src/components/ValueSet/ValueSetForm.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
🧰 Additional context used
🪛 GitHub Check: lint
src/components/ValueSet/ValueSetForm.tsx

[failure] 516-516:
Delete ··⏎······

🪛 ESLint
src/components/ValueSet/ValueSetForm.tsx

[error] 516-517: Delete ··⏎······

(prettier/prettier)

🪛 GitHub Actions: Lint Code Base
src/components/ValueSet/ValueSetForm.tsx

[error] 516-516: Prettier formatting check failed. Delete ··⏎······.

🪛 GitHub Actions: Cypress Tests
src/components/ValueSet/ValueSetForm.tsx

[error] 504-504: TS2304: Cannot find name 'goBack'.

🔇 Additional comments (2)
src/components/ValueSet/ValueSetForm.tsx (2)

342-351: Well-implemented validation enhancements with proper internationalization

The validation schema for name and slug fields has been appropriately enhanced:

  • Added .trim() to both fields to handle whitespace properly
  • Implemented minimum and maximum length validations for the slug field
  • Added a regex pattern to enforce proper slug format (alphanumeric characters, hyphens, and underscores only)
  • Used translation functions consistently for all error messages

This implementation aligns with the PR objectives to add validations to the Name and Slug fields.


347-349: Verify minimum length validation error message

The slug field has a minimum length of 5 characters but uses the generic field_required error message which may not accurately convey the minimum length requirement to users.

Consider using a more specific error message that communicates the minimum length requirement:

- .min(5, t("field_required"))
+ .min(5, t("min_character_validation", { length: 5 }))

This assumes you have a translation key for minimum character validation similar to the maximum character validation key you're already using.

@@ -394,15 +399,14 @@
),
}),
});

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove trailing blank line

There's an extra blank line after the schema definition which needs to be removed to comply with the project's code style.

-
📝 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
// (The file now has no trailing blank line)

@@ -509,6 +513,7 @@
{isSubmitting ? t("saving") : t("save_valueset")}
</Button>
</div>

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove trailing whitespace

There's trailing whitespace on this line that needs to be removed to comply with the project's code style.

-        
+
📝 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
🧰 Tools
🪛 GitHub Check: lint

[failure] 516-516:
Delete ··⏎······

🪛 ESLint

[error] 516-517: Delete ··⏎······

(prettier/prettier)

🪛 GitHub Actions: Lint Code Base

[error] 516-516: Prettier formatting check failed. Delete ··⏎······.

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Mar 5, 2025
@nihal467
Copy link
Member

nihal467 commented Mar 6, 2025

image

@hrit2773

  • the translation are missing add them for the error message
  • look into code rabbit comment

@hrit2773
Copy link
Contributor Author

hrit2773 commented Mar 6, 2025

@nihal467 Now it should work can you validate it again.

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.

Valueset create/edit name field needs further validation
6 participants