From 5ebdcb1553e00272bde4d693b141ce593e4c3a4f Mon Sep 17 00:00:00 2001 From: Jakub Kosmydel <104823336+kosmydel@users.noreply.github.com> Date: Thu, 14 Mar 2024 10:02:39 +0100 Subject: [PATCH] extract validation --- src/libs/ValidationUtils.ts | 19 ++++++++++++++++++- .../workspace/taxes/WorkspaceNewTaxPage.tsx | 7 ++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/libs/ValidationUtils.ts b/src/libs/ValidationUtils.ts index 3d5f23a84f74..5876ccf5d7d7 100644 --- a/src/libs/ValidationUtils.ts +++ b/src/libs/ValidationUtils.ts @@ -8,7 +8,7 @@ import type {OnyxCollection} from 'react-native-onyx'; import type {FormInputErrors, FormOnyxKeys, FormOnyxValues, FormValue} from '@components/Form/types'; import CONST from '@src/CONST'; import type {OnyxFormKey} from '@src/ONYXKEYS'; -import type {Report} from '@src/types/onyx'; +import type {Report, TaxRates} from '@src/types/onyx'; import * as CardUtils from './CardUtils'; import DateUtils from './DateUtils'; import type {MaybePhraseKey} from './Localize'; @@ -460,6 +460,21 @@ function prepareValues(values: ValuesType): ValuesType { return trimmedStringValues; } +/** + * Validates the given value if it is correct percentage value. + */ +function isValidPercentage(value: string): boolean { + const parsedValue = Number(value); + return !Number.isNaN(parsedValue) && parsedValue >= 0 && parsedValue <= 100; +} + +/** + * Validates the given value if it is correct tax name. + */ +function isExistingTaxName(value: string, taxRates: TaxRates): boolean { + return !!Object.values(taxRates).find((taxRate) => taxRate.name === value); +} + export { meetsMinimumAgeRequirement, meetsMaximumAgeRequirement, @@ -498,4 +513,6 @@ export { validateDateTimeIsAtLeastOneMinuteInFuture, prepareValues, isValidPersonName, + isValidPercentage, + isExistingTaxName, }; diff --git a/src/pages/workspace/taxes/WorkspaceNewTaxPage.tsx b/src/pages/workspace/taxes/WorkspaceNewTaxPage.tsx index cd226554c364..9586425b5a8c 100644 --- a/src/pages/workspace/taxes/WorkspaceNewTaxPage.tsx +++ b/src/pages/workspace/taxes/WorkspaceNewTaxPage.tsx @@ -38,12 +38,13 @@ function WorkspaceNewTaxPage({ (values: FormOnyxValues): FormInputErrors => { const errors = ValidationUtils.getFieldRequiredErrors(values, [INPUT_IDS.VALUE, INPUT_IDS.NAME]); - const value = Number(values[INPUT_IDS.VALUE]); - if (value > 100 || value < 0) { + const value = values[INPUT_IDS.VALUE]; + if (!ValidationUtils.isValidPercentage(value)) { errors[INPUT_IDS.VALUE] = 'workspace.taxes.errors.valuePercentageRange'; } - if (Object.values(policy?.taxRates?.taxes ?? {}).find((tax) => tax.name === values[INPUT_IDS.NAME])) { + const name = values[INPUT_IDS.NAME]; + if (policy?.taxRates?.taxes && ValidationUtils.isExistingTaxName(name, policy.taxRates.taxes)) { errors[INPUT_IDS.NAME] = 'workspace.taxes.errors.taxRatealreadyExists'; }