Skip to content

Commit

Permalink
extract validation
Browse files Browse the repository at this point in the history
  • Loading branch information
kosmydel committed Mar 14, 2024
1 parent 2747599 commit 5ebdcb1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
19 changes: 18 additions & 1 deletion src/libs/ValidationUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -498,4 +513,6 @@ export {
validateDateTimeIsAtLeastOneMinuteInFuture,
prepareValues,
isValidPersonName,
isValidPercentage,
isExistingTaxName,
};
7 changes: 4 additions & 3 deletions src/pages/workspace/taxes/WorkspaceNewTaxPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@ function WorkspaceNewTaxPage({
(values: FormOnyxValues<typeof ONYXKEYS.FORMS.WORKSPACE_NEW_TAX_FORM>): FormInputErrors<typeof ONYXKEYS.FORMS.WORKSPACE_NEW_TAX_FORM> => {
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';
}

Expand Down

0 comments on commit 5ebdcb1

Please sign in to comment.