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

DOB Values Limit in patient registration form #9735

Open
wants to merge 18 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions public/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"CONSCIOUSNESS_LEVEL__RESPONDS_TO_VOICE": "Responds to Voice",
"CONSCIOUSNESS_LEVEL__UNRESPONSIVE": "Unresponsive",
"Cancel": "Cancel",
Rishith25 marked this conversation as resolved.
Show resolved Hide resolved
"DATE_NOT_ALLOWED": "Date must be on or before today's date. Please correct the date.",
"DAYS_OF_WEEK_SHORT__0": "Mon",
"DAYS_OF_WEEK_SHORT__1": "Tue",
"DAYS_OF_WEEK_SHORT__2": "Wed",
Expand Down Expand Up @@ -70,6 +71,10 @@
"INSULIN_INTAKE_FREQUENCY__OD": "Once a day (OD)",
"INSULIN_INTAKE_FREQUENCY__TD": "Thrice a day (TD)",
"INSULIN_INTAKE_FREQUENCY__UNKNOWN": "Unknown",
"INVALID_DATE": "Invalid day for the selected month and year. Please correct the date.",
"INVALID_DAY": "Invalid day value. Please enter a valid day.",
"INVALID_MONTH": "Invalid month value. Please enter a valid month.",
"INVALID_YEAR": "Year not in range. Please enter a valid year.",
"ISOLATION": "Isolation",
"LIMB_RESPONSE__EXTENSION": "Extension",
"LIMB_RESPONSE__FLEXION": "Flexion",
Expand Down
189 changes: 135 additions & 54 deletions src/components/Patient/PatientRegistration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ export default function PatientRegistration(
useState(!!patientId);
const [debouncedNumber, setDebouncedNumber] = useState<string>();

const MIN_YEAR = 1900;
const MAX_YEAR = new Date().getFullYear();

const sidebarItems = [
{ label: t("patient__general-info"), id: "general-info" },
// { label: t("social_profile"), id: "social-profile" },
Expand Down Expand Up @@ -274,6 +277,93 @@ export default function PatientRegistration(
}
};

const isLeapYear = (year: number): boolean => {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
};

const isValidDate = (day: number, month: number, year: number): boolean => {
const monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (month === 2) {
return day <= (isLeapYear(year) ? 29 : 28);
}
return day <= monthDays[month - 1];
};

const handleDateOfBirth = (
Rishith25 marked this conversation as resolved.
Show resolved Hide resolved
part: "day" | "month" | "year",
value: string,
min: number,
max: number,
maxLength: number,
) => {
if (value.length > maxLength) {
value = value.slice(0, maxLength);
}
const numericValue = Number(value.slice(0, maxLength));

setForm((prevState) => {
const [currentYear, currentMonth, currentDay] =
prevState.date_of_birth?.split("-") || ["", "", ""];

let formattedValue = value;
let errorMessage = "";

if (part === "day") {
if (numericValue < min || numericValue > max) {
formattedValue = "";
errorMessage = t("INVALID_DAY");
}
} else if (part === "month") {
if (numericValue < min || numericValue > max) {
formattedValue = "";
errorMessage = t("INVALID_MONTH");
}
} else if (part === "year") {
if (formattedValue.length === 4) {
const yearValue = Number(formattedValue);

if (yearValue < min || yearValue > max) {
formattedValue = "";
errorMessage = t("INVALID_YEAR", { min: MIN_YEAR, max: MAX_YEAR });
}
}
}

const updatedDay = part === "day" ? formattedValue : currentDay;
const updatedMonth = part === "month" ? formattedValue : currentMonth;
const updatedYear = part === "year" ? formattedValue : currentYear;

if (updatedDay && updatedMonth && updatedYear) {
const day = Number(updatedDay);
const month = Number(updatedMonth);
const year = Number(updatedYear);

if (!isValidDate(day, month, year)) {
errorMessage = t("INVALID_DATE");
} else {
const today = new Date();
const selectedDate = new Date(year, month - 1, day);

if (selectedDate > today) {
errorMessage = t("DATE_NOT_ALLOWED");
}
}
}

setFeErrors((errors) => ({
...errors,
date_of_birth: errorMessage ? [errorMessage] : [],
}));

const updatedDate = `${updatedYear}-${updatedMonth}-${updatedDay}`;

return {
...prevState,
date_of_birth: updatedDate,
};
});
};

useEffect(() => {
const handler = setTimeout(() => {
if (!patientId || patientQuery.data?.phone_number !== form.phone_number) {
Expand Down Expand Up @@ -446,60 +536,51 @@ export default function PatientRegistration(
</TabsList>
<TabsContent value="dob">
<div className="flex items-center gap-2">
<div className="flex-1">
<InputWithError label={t("day")} required>
<Input
placeholder="DD"
type="number"
value={form.date_of_birth?.split("-")[2] || ""}
maxLength={2}
max={31}
min={1}
onChange={(e) =>
setForm((f) => ({
...f,
date_of_birth: `${form.date_of_birth?.split("-")[0] || ""}-${form.date_of_birth?.split("-")[1] || ""}-${e.target.value}`,
}))
}
/>
</InputWithError>
</div>
<div className="flex-1">
<InputWithError label={t("month")} required>
<Input
placeholder="MM"
type="number"
value={form.date_of_birth?.split("-")[1] || ""}
maxLength={2}
max={12}
min={1}
onChange={(e) =>
setForm((f) => ({
...f,
date_of_birth: `${form.date_of_birth?.split("-")[0] || ""}-${e.target.value}-${form.date_of_birth?.split("-")[2] || ""}`,
}))
}
/>
</InputWithError>
</div>
<div className="flex-1">
<InputWithError label={t("year")} required>
<Input
type="number"
placeholder="YYYY"
value={form.date_of_birth?.split("-")[0] || ""}
maxLength={4}
max={new Date().getFullYear()}
min={1900}
onChange={(e) =>
setForm((f) => ({
...f,
date_of_birth: `${e.target.value}-${form.date_of_birth?.split("-")[1] || ""}-${form.date_of_birth?.split("-")[2] || ""}`,
}))
}
/>
</InputWithError>
</div>
{["day", "month", "year"].map((part) => {
const key = part as "day" | "month" | "year";
const placeholders = {
day: "DD",
month: "MM",
year: "YYYY",
};
const maxLengths = { day: 2, month: 2, year: 4 };
const limits = {
day: { min: 1, max: 31 },
month: { min: 1, max: 12 },
year: { min: MIN_YEAR, max: MAX_YEAR },
};

return (
<div className="flex-1" key={key}>
<InputWithError label={t(key)} required>
<Input
type="number"
placeholder={placeholders[key]}
value={
form.date_of_birth?.split("-")[
["year", "month", "day"].indexOf(key)
] || ""
}
maxLength={maxLengths[key]}
max={limits[key].max}
min={limits[key].min}
onChange={(e) => {
const value = e.target.value;
if (key !== "year" || value.length <= 4) {
handleDateOfBirth(
key,
value,
limits[key].min,
limits[key].max,
maxLengths[key],
);
}
}}
/>
</InputWithError>
</div>
);
})}
</div>
{errors["date_of_birth"] && (
<InputErrors errors={errors["date_of_birth"]} />
Expand Down
Loading