-
Notifications
You must be signed in to change notification settings - Fork 515
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
robustify UserCreateForm
#9852
robustify UserCreateForm
#9852
Conversation
WalkthroughThis pull request introduces comprehensive validation improvements across multiple components and localization files. The changes focus on enhancing user input validation for forms, particularly in user creation, patient registration, and form submissions. Key improvements include adding validation messages for username, phone number, and date of birth fields, preventing future date selections, disabling submit buttons when no changes are made, and ensuring non-negative age inputs. Changes
Assessment against linked issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for care-ohc ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🔭 Outside diff range comments (1)
src/components/Users/CreateUserForm.tsx (1)
Line range hint
112-114
: Initializealt_phone_number
to an empty string to prevent incomplete submissions.Setting the default value of
alt_phone_number
to"+91"
may result in submitting an incomplete phone number if the user doesn't modify this field. Initializing it to an empty string ensures that validation will prompt the user if necessary.Apply this diff to correct the default value:
defaultValues: { user_type: "staff", phone_number: "+91", - alt_phone_number: "+91", + alt_phone_number: "", phone_number_is_whatsapp: true, gender: "male", },
🧹 Nitpick comments (1)
src/components/Users/CreateUserForm.tsx (1)
83-85
: Ensure date comparison fordate_of_birth
excludes time component.Comparing
date_of_birth
directly withnew Date()
includes time components, which may cause issues due to time zone differences. To accurately validate dates, compare only the date parts.Apply this diff to refine the date comparison:
.refine((dob) => dob <= new Date(), { message: t("date_of_birth_cannot_be_in_future"), }), + .refine((dob) => dob >= new Date("1900-01-01"), { + message: t("date_of_birth_cannot_be_before_1900"), + }),Alternatively, strip the time component when performing the comparison.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
public/locale/en.json
(4 hunks)src/components/Users/CreateUserForm.tsx
(13 hunks)src/components/ui/date-picker.tsx
(2 hunks)src/types/user/user.ts
(1 hunks)src/types/user/userApi.ts
(2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: OSSAR-Scan
🔇 Additional comments (5)
src/types/user/userApi.ts (1)
4-4
: LGTM!The request body type for the
create
endpoint has been correctly updated toUserCreateRequest
, ensuring the API call aligns with the expected data structure.Also applies to: 16-16
src/components/ui/date-picker.tsx (1)
19-19
: Well-implemented date validation enhancement!The addition of the
disabled
prop is a clean and flexible solution that:
- Provides a type-safe way to implement date validation
- Follows React's functional programming patterns
- Properly propagates the validation to the underlying Calendar component
Also applies to: 22-22, 48-48
public/locale/en.json (3)
672-672
: LGTM: Clear date validation message!The message is user-friendly and clearly explains the validation rule.
1420-1420
: LGTM: Clear phone number format requirement!The message explicitly states the expected format (+91 followed by 10 digits).
1868-1873
: LGTM: Comprehensive username validation messages!The messages clearly explain all username requirements:
- Length constraints (4-16 characters)
- Allowed characters (lowercase, numbers, dots, underscores, hyphens)
- Special character rules (no consecutive ones, must start/end with alphanumeric)
There was a problem hiding this 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
🧹 Nitpick comments (2)
src/components/Schedule/ScheduleExceptionForm.tsx (1)
255-259
: Good addition of form dirty state check!The addition of
form.formState.isDirty
check prevents unnecessary form submissions and provides better UX feedback. Consider adding a tooltip to explain why the button is disabled when the form is pristine.<Button variant="primary" type="submit" disabled={isPending || !form.formState.isDirty} + title={!form.formState.isDirty ? "No changes to save" : ""} >
src/components/Facility/FacilityCreate.tsx (1)
Line range hint
255-259
: Consider form-specific state management patterns.The addition of form dirty state checks shows a good intention to prevent unnecessary submissions. However, the implementation should be adjusted based on the form's purpose:
- For edit/update forms: Keep the dirty state check
- For create forms: Use validation state instead
- For dual-purpose forms: Apply conditional logic
This will provide a more intuitive user experience across different form types.
Also applies to: 322-326, 421-425, 506-510
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/components/Encounter/CreateEncounterForm.tsx
(1 hunks)src/components/Facility/CreateFacilityForm.tsx
(1 hunks)src/components/Facility/FacilityCreate.tsx
(1 hunks)src/components/Schedule/ScheduleExceptionForm.tsx
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: OSSAR-Scan
There was a problem hiding this 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 comments (1)
src/components/Patient/PatientRegistration.tsx (1)
Consider splitting the PatientRegistration component for better maintainability
The component, while functional, handles too many responsibilities and could benefit from being split into smaller, focused components:
- Create separate components for each form section (general info, address, contact details)
- Extract form state management logic into custom hooks
- Consider using form management libraries like react-hook-form or formik
The application already has proper error boundaries at the router level and adequate security measures in place.
🔗 Analysis chain
Line range hint
1-1000
: Consider architectural improvements for better maintainability and security.
- The component is handling too many responsibilities. Consider splitting it into smaller components for each section.
- Add server-side validation to complement client-side validation.
- Implement error boundaries to gracefully handle rendering failures.
- Consider adding CSRF protection to mutations.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for CSRF token usage in API calls rg -A 5 "useMutation|useQuery" | rg "csrf" # Check component size and complexity ast-grep --pattern 'export default function PatientRegistration' -A 1000 | wc -lLength of output: 127
Script:
#!/bin/bash # Check request utilities for CSRF implementation rg -p "csrf" src/Utils/request/ # Check component size with a more specific pattern rg -p "^export default function PatientRegistration" -A 1000 "src/components/Patient/PatientRegistration.tsx" # Look for error boundary implementations rg -p "ErrorBoundary" src/Length of output: 32332
Script:
#!/bin/bash # Check request utilities implementation rg -p "mutate|query" "src/Utils/request/" # Check for any security headers or tokens in API calls rg -p "headers|token" "src/Utils/request/"Length of output: 5920
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Patient/PatientRegistration.tsx
(1 hunks)
🔇 Additional comments (1)
src/components/Patient/PatientRegistration.tsx (1)
Line range hint
1-1000
: Add comprehensive test coverage.The component lacks test coverage for critical functionality:
- Age validation and year calculation
- Form submission and error handling
- Duplicate patient detection
- Phone number validation
Would you like me to help create a test suite for this component? I can generate comprehensive tests covering all the critical paths.
👋 Hi, @rajku-dev, This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there. |
There was a problem hiding this 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/Users/CreateUserForm.tsx (1)
89-95
: Enhance date of birth validation.The date validation correctly prevents future dates but could be improved by:
- Adding a reasonable minimum date (e.g., 120 years ago)
- Adding a minimum age requirement if applicable
date_of_birth: z .date({ required_error: t("this_field_is_required"), }) .refine((dob) => dob <= new Date(), { message: t("date_of_birth_cannot_be_in_future"), + }) + .refine((dob) => dob >= new Date(new Date().setFullYear(new Date().getFullYear() - 120)), { + message: t("date_of_birth_too_old"), + }) + .refine((dob) => dob <= new Date(new Date().setFullYear(new Date().getFullYear() - 13)), { + message: t("minimum_age_required"), }),
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
public/locale/en.json
(4 hunks)src/components/Facility/CreateFacilityForm.tsx
(1 hunks)src/components/Users/CreateUserForm.tsx
(14 hunks)src/types/user/userApi.ts
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/types/user/userApi.ts
- src/components/Facility/CreateFacilityForm.tsx
🧰 Additional context used
🪛 GitHub Check: lint
src/components/Users/CreateUserForm.tsx
[failure] 3-3:
Replace Loader2·}·from·"lucide-react
with useQuery·}·from·"@tanstack/react-query
[failure] 4-4:
Replace useQuery·}·from·"@tanstack/react-query
with Loader2·}·from·"lucide-react
[failure] 37-37:
Replace ⏎import·mutate·from·"@/Utils/request/mutate";⏎import·*·as·Notification·from·"@/Utils/Notifications
with import·*·as·Notification·from·"@/Utils/Notifications";⏎import·mutate·from·"@/Utils/request/mutate
🪛 eslint
src/components/Users/CreateUserForm.tsx
[error] 3-3: Replace Loader2·}·from·"lucide-react
with useQuery·}·from·"@tanstack/react-query
(prettier/prettier)
[error] 4-4: Replace useQuery·}·from·"@tanstack/react-query
with Loader2·}·from·"lucide-react
(prettier/prettier)
[error] 37-39: Replace ⏎import·mutate·from·"@/Utils/request/mutate";⏎import·*·as·Notification·from·"@/Utils/Notifications
with import·*·as·Notification·from·"@/Utils/Notifications";⏎import·mutate·from·"@/Utils/request/mutate
(prettier/prettier)
🪛 GitHub Actions: Lint Code Base
src/components/Users/CreateUserForm.tsx
[error] 3-3: Replace Loader2
with useQuery
from @tanstack/react-query (prettier/prettier)
🔇 Additional comments (6)
src/components/Users/CreateUserForm.tsx (5)
79-79
: Consider supporting international phone numbers instead of hardcoding '+91'.This issue was previously identified. The current validation restricts phone numbers to Indian format only, limiting the application's international usability.
182-188
: Improve error handling in the mutation'sonError
callback.The current error handling assumes a specific error structure which may lead to runtime errors if the API response doesn't match the expected format.
191-208
: Serializedate_of_birth
before sending in API request.The
date_of_birth
field needs to be serialized to ISO string format before sending to the API.
518-526
: Well implemented submit button logic!The button implementation follows best practices:
- Prevents duplicate submissions using
isPending
- Shows loading state with spinner
- Properly disables when form is invalid or pristine
244-244
: Excellent form field labeling!The form fields follow accessibility best practices:
- Required fields are properly marked
- Labels are properly translated
- FormLabel components are used consistently
Also applies to: 258-258, 272-272, 289-289, 307-307, 326-326, 341-341, 360-360, 402-402
public/locale/en.json (1)
677-677
: Well-written validation messages!The new validation messages are:
- Clear and user-friendly
- Properly formatted
- Consistent with existing messages
Also applies to: 1433-1433, 1768-1768, 1892-1897
There was a problem hiding this 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 (3)
src/components/Users/CreateUserForm.tsx (3)
85-92
: Enhance date of birth validation.The date validation can be improved by:
- Making the minimum date configurable instead of hardcoding "1900-01-01"
- Adding a reasonable maximum age validation
date_of_birth: z .date({ required_error: t("this_field_is_required"), }) .refine((dob) => dob <= new Date(), { message: t("date_of_birth_cannot_be_in_future"), + }) + .refine((dob) => { + const minDate = new Date(); + minDate.setFullYear(minDate.getFullYear() - 120); // Max age of 120 years + return dob >= minDate; + }, { + message: t("date_of_birth_too_old"), }),
Line range hint
128-137
: Improve WhatsApp number synchronization.The current implementation directly sets the alt_phone_number when isWhatsApp changes. Consider adding a confirmation dialog when switching from WhatsApp mode to prevent accidental data loss.
useEffect(() => { if (isWhatsApp) { form.setValue("alt_phone_number", phoneNumber); + form.trigger("alt_phone_number"); } + // Don't clear alt_phone_number when disabling WhatsApp mode + // to prevent accidental data loss if (usernameInput && usernameInput.length > 0) { form.trigger("username"); } }, [phoneNumber, isWhatsApp, form, usernameInput]);
340-345
: Standardize input restrictions across phone number fields.Both phone number inputs should have consistent maxLength and type restrictions.
<Input type="tel" placeholder="+91XXXXXXXXXX" maxLength={13} + pattern="[+][0-9]{12}" {...field} /> // In alt_phone_number input <Input placeholder="+91XXXXXXXXXX" type="tel" {...field} maxLength={13} + pattern="[+][0-9]{12}" disabled={isWhatsApp} />Also applies to: 363-365
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Users/CreateUserForm.tsx
(13 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/components/Users/CreateUserForm.tsx (4)
74-84
: Consider supporting international phone numbers.The phone number validation is currently restricted to Indian numbers (+91). This limits the application's international usability.
179-185
: Improve error handling in the mutation'sonError
callback.The current error handling assumes a specific error structure which could lead to runtime errors.
188-205
: Serializedate_of_birth
before sending in API request.The
date_of_birth
field needs to be serialized to ISO string format before sending to the API.
515-523
: LGTM! Well-implemented submit button state management.The submit button correctly handles:
- Form validation state
- Dirty state tracking
- Loading indicator
- Proper disable conditions
👋 Hi, @rajku-dev, This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there. |
Please review the changes @Jacobjeevan |
There was a problem hiding this 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 (2)
public/locale/en.json (2)
1454-1454
: Consider parameterizing the country code.The message hardcodes "+91" which makes it less reusable for other country codes. Consider parameterizing this value for better internationalization support.
- "phone_number_must_start": "Phone number must start with +91 followed by 10 digits", + "phone_number_must_start": "Phone number must start with {{countryCode}} followed by {{digitCount}} digits",
1921-1926
: Standardize the phrasing of username validation messages.The username validation messages would benefit from consistent phrasing. Some use contractions ("can't") while others don't ("must be"). Consider standardizing:
- "username_consecutive_special_characters": "Username can't contain consecutive special characters", + "username_consecutive_special_characters": "Username must not contain consecutive special characters", - "username_contain_lowercase_special": "Username can only contain lowercase letters, numbers, and . _ -", + "username_contain_lowercase_special": "Username must only contain lowercase letters, numbers, and . _ -", "username_less_than": "Username must be less than 16 characters", "username_more_than": "Username must be at least 4 characters", "username_start_end_letter_number": "Username must start and end with a letter or number"
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
public/locale/en.json
(4 hunks)src/components/Facility/CreateFacilityForm.tsx
(1 hunks)src/components/Facility/FacilityCreate.tsx
(1 hunks)src/components/Patient/PatientRegistration.tsx
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- src/components/Facility/CreateFacilityForm.tsx
- src/components/Facility/FacilityCreate.tsx
- src/components/Patient/PatientRegistration.tsx
🔇 Additional comments (2)
public/locale/en.json (2)
683-683
: LGTM! Clear validation message.The validation message for date of birth is clear, concise, and follows the established format.
1796-1796
: LGTM! Generic validation message.The generic required field message is reusable and follows standard validation message format.
There was a problem hiding this 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 (2)
public/locale/en.json (2)
1461-1461
: Consider making phone validation more flexible for international numbers.The current validation message is specific to Indian phone numbers (+91). Consider making it more generic to support international phone numbers, especially if the application might be used globally in the future.
- "phone_number_must_start": "Phone number must start with +91 followed by 10 digits", + "phone_number_must_start": "Phone number must start with country code (e.g., +91) followed by the number",
1930-1935
: LGTM! Comprehensive username validation rules.The username validation messages are clear, specific, and follow security best practices. Consider adding example messages to help users understand the rules better.
Add example messages to illustrate valid and invalid usernames:
"username_consecutive_special_characters": "Username can't contain consecutive special characters", + "username_consecutive_special_characters_example": "Example: 'john.doe' is valid, 'john..doe' is not", "username_contain_lowercase_special": "Username can only contain lowercase letters, numbers, and . _ -", + "username_contain_lowercase_special_example": "Example: 'john.doe_123' is valid", "username_less_than": "Username must be less than 16 characters", "username_more_than": "Username must be at least 4 characters", + "username_length_example": "Example: 'john' to 'john.doe.smith'", "username_start_end_letter_number": "Username must start and end with a letter or number" + "username_start_end_letter_number_example": "Example: 'john.doe' is valid, '.john.' is not"
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
public/locale/en.json
(4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: Redirect rules - care-ohc
- GitHub Check: Header rules - care-ohc
- GitHub Check: Pages changed - care-ohc
- GitHub Check: CodeQL-Build
- GitHub Check: cypress-run (1)
- GitHub Check: OSSAR-Scan
🔇 Additional comments (2)
public/locale/en.json (2)
683-683
: LGTM! Clear validation message.The validation message for preventing future dates in date of birth is clear and user-friendly.
1808-1808
: LGTM! Standard required field message.The generic required field validation message follows common UX patterns and can be reused across different form fields.
👋 Hi, @rajku-dev, This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there. |
There was a problem hiding this 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)
src/components/Schedule/ScheduleExceptionForm.tsx (1)
Line range hint
76-105
: Add error handling and simplify success handling.The mutation setup should include error handling, and the success effect could be more concise:
const { mutate: createException, isPending, isSuccess, + error, } = useMutation({ mutationFn: mutate(ScheduleAPIs.exceptions.create, { pathParams: { facility_id: facilityId }, }), + onSuccess: () => { + toast.success("Exception created successfully"); + setOpen(false); + form.reset(); + onRefresh?.(); + }, + onError: (error) => { + toast.error(error.message || "Failed to create exception"); + }, }); -useEffect(() => { - if (isSuccess) { - toast.success("Exception created successfully"); - setOpen(false); - form.reset(); - onRefresh?.(); - } -}, [isSuccess]);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Schedule/ScheduleExceptionForm.tsx
(5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: cypress-run (1)
- GitHub Check: OSSAR-Scan
🔇 Additional comments (4)
src/components/Schedule/ScheduleExceptionForm.tsx (4)
31-34
: LGTM! Import statements are well-organized.The new imports for
ScheduleAPIs
,useSlug
, andUserBase
align well with the component's functionality.Also applies to: 38-38
55-58
: LGTM! Props and component structure improvements.Good improvements:
- Component name better reflects its purpose
- Props interface is more focused with
user
and optionalonRefresh
- Facility ID is properly obtained from the
useSlug
hookAlso applies to: 60-62
121-123
: LGTM! Clean UI implementation with proper button states.The UI implementation follows best practices:
- Responsive form layout
- Proper button states with loading indicators
- Clear action labels
Also applies to: 252-256
60-60
: Verify component usage across the codebase.Let's ensure this component is used consistently and all callers provide the required props.
✅ Verification successful
Component usage is consistent and correct
The
ScheduleExceptionForm
component is properly used inUserAvailabilityTab.tsx
with all required props being provided. No issues were found in the implementation or usage patterns.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for component usage rg -l "ScheduleExceptionForm|CreateScheduleExceptionSheet" --type ts --type tsx # Search for any direct API calls that might bypass this component rg "exceptions.create" --type ts --type tsxLength of output: 181
Script:
#!/bin/bash # Find all TypeScript and React TypeScript files echo "TypeScript and React files:" fd "\.(ts|tsx)$" # Search for component usage echo -e "\nComponent usage:" rg "ScheduleExceptionForm|CreateScheduleExceptionSheet" # Search for API calls echo -e "\nAPI calls:" rg "exceptions\.create"Length of output: 18502
const formSchema = z.object({ | ||
reason: z.string().min(1, "Reason is required"), | ||
valid_from: z.date({ required_error: "From date is required" }), | ||
valid_to: z.date({ required_error: "To date is required" }), | ||
start_time: z | ||
.string() | ||
.min(1, "Start time is required") as unknown as z.ZodType<Time>, | ||
end_time: z | ||
.string() | ||
.min(1, "End time is required") as unknown as z.ZodType<Time>, | ||
unavailable_all_day: z.boolean(), | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add missing validation rules to prevent invalid schedule exceptions.
The form schema should include additional validation rules to ensure data integrity:
- Validate that the end date is after or equal to the start date
- Validate that the end time is after the start time (when not all day)
- Prevent past dates from being selected
const formSchema = z.object({
reason: z.string().min(1, "Reason is required"),
valid_from: z.date({ required_error: "From date is required" })
+ .min(new Date(), "Date cannot be in the past"),
valid_to: z.date({ required_error: "To date is required" })
+ .min(new Date(), "Date cannot be in the past"),
start_time: z
.string()
.min(1, "Start time is required") as unknown as z.ZodType<Time>,
end_time: z
.string()
.min(1, "End time is required") as unknown as z.ZodType<Time>,
unavailable_all_day: z.boolean(),
+ }).refine(
+ (data) => {
+ return data.valid_to >= data.valid_from;
+ },
+ {
+ message: "End date must be after or equal to start date",
+ path: ["valid_to"],
+ }
+ ).refine(
+ (data) => {
+ if (data.unavailable_all_day) return true;
+ return data.end_time > data.start_time;
+ },
+ {
+ message: "End time must be after start time",
+ path: ["end_time"],
+ }
);
📝 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.
const formSchema = z.object({ | |
reason: z.string().min(1, "Reason is required"), | |
valid_from: z.date({ required_error: "From date is required" }), | |
valid_to: z.date({ required_error: "To date is required" }), | |
start_time: z | |
.string() | |
.min(1, "Start time is required") as unknown as z.ZodType<Time>, | |
end_time: z | |
.string() | |
.min(1, "End time is required") as unknown as z.ZodType<Time>, | |
unavailable_all_day: z.boolean(), | |
}); | |
const formSchema = z.object({ | |
reason: z.string().min(1, "Reason is required"), | |
valid_from: z.date({ required_error: "From date is required" }) | |
.min(new Date(), "Date cannot be in the past"), | |
valid_to: z.date({ required_error: "To date is required" }) | |
.min(new Date(), "Date cannot be in the past"), | |
start_time: z | |
.string() | |
.min(1, "Start time is required") as unknown as z.ZodType<Time>, | |
end_time: z | |
.string() | |
.min(1, "End time is required") as unknown as z.ZodType<Time>, | |
unavailable_all_day: z.boolean(), | |
}).refine( | |
(data) => { | |
return data.valid_to >= data.valid_from; | |
}, | |
{ | |
message: "End date must be after or equal to start date", | |
path: ["valid_to"], | |
} | |
).refine( | |
(data) => { | |
if (data.unavailable_all_day) return true; | |
return data.end_time > data.start_time; | |
}, | |
{ | |
message: "End time must be after start time", | |
path: ["end_time"], | |
} | |
); |
Proposed Changes
CreateUserForm
and add dirtyState to all react-hook-form #9749@ohcnetwork/care-fe-code-reviewers
Merge Checklist
Summary by CodeRabbit
New Features
Bug Fixes
Localization