Skip to content

Commit

Permalink
add switch and data field
Browse files Browse the repository at this point in the history
add whole number validation

refactor: semantically simpler validation
  • Loading branch information
RODO94 committed Oct 10, 2024
1 parent aad9a43 commit 9fd0a03
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
23 changes: 18 additions & 5 deletions editor.planx.uk/src/@planx/components/NumberInput/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ import Switch from "@mui/material/Switch";
import { ComponentType as TYPES } from "@opensystemslab/planx-core/types";
import type { NumberInput } from "@planx/components/NumberInput/model";
import { parseNumberInput } from "@planx/components/NumberInput/model";
import {
EditorProps,
ICONS,
} from "@planx/components/ui";
import { EditorProps, ICONS } from "@planx/components/ui";
import { useFormik } from "formik";
import React from "react";
import { ModalFooter } from "ui/editor/ModalFooter";
Expand Down Expand Up @@ -83,14 +80,30 @@ export default function NumberInputComponent(props: Props): FCReturn {
onChange={() =>
formik.setFieldValue(
"allowNegatives",
!formik.values.allowNegatives,
!formik.values.allowNegatives
)
}
/>
}
label="Allow negative numbers to be input"
/>
</InputRow>
<InputRow>
<FormControlLabel
control={
<Switch
checked={formik.values.onlyWholeNumbers}
onChange={() =>
formik.setFieldValue(
"onlyWholeNumbers",
!formik.values.onlyWholeNumbers
)
}
/>
}
label="Only allow whole numbers"
/>
</InputRow>
</ModalSectionContent>
</ModalSection>
<ModalFooter formik={formik} />
Expand Down
17 changes: 16 additions & 1 deletion editor.planx.uk/src/@planx/components/NumberInput/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface NumberInput extends BaseNodeData {
fn?: string;
units?: string;
allowNegatives?: boolean;
onlyWholeNumbers?: boolean;
}

export type UserData = number;
Expand All @@ -21,13 +22,14 @@ export const parseNumber = (raw: string): number | null => {
};

export const parseNumberInput = (
data: Record<string, any> | undefined,
data: Record<string, any> | undefined
): NumberInput => ({
title: data?.title || "",
description: data?.description,
fn: data?.fn || "",
units: data?.units,
allowNegatives: data?.allowNegatives || false,
onlyWholeNumbers: data?.onlyWholeNumbers || false,
...parseBaseNodeData(data),
});

Expand All @@ -52,6 +54,19 @@ export const numberInputValidationSchema = (input: NumberInput) =>
}
return value === "0" ? true : Boolean(parseNumber(value));
},
})
.test({
name: "check for a whole number",
message: "Enter a whole number",
test: (value: string | undefined) => {
if (!value) {
return false;
}
if (!Number.isInteger(Number(value))) {
return false;
}
return true;
},
});

export const validationSchema = (input: NumberInput) =>
Expand Down

0 comments on commit 9fd0a03

Please sign in to comment.