2022-08-04 13:34:30 +02:00
|
|
|
import {
|
|
|
|
IStrategyParameter,
|
|
|
|
IFeatureStrategyParameters,
|
|
|
|
} from 'interfaces/strategy';
|
|
|
|
|
|
|
|
export const validateParameterValue = (
|
2022-08-22 16:35:51 +02:00
|
|
|
definition: Pick<IStrategyParameter, 'type' | 'required'>,
|
2023-10-02 14:25:46 +02:00
|
|
|
value: IFeatureStrategyParameters[string],
|
2022-08-04 13:34:30 +02:00
|
|
|
): string | undefined => {
|
|
|
|
const { type, required } = definition;
|
|
|
|
|
2022-08-24 10:38:08 +02:00
|
|
|
// Some input components in the feature strategy form can't show error messages.
|
|
|
|
// We should not validate those fields until their errors can be shown in the UI.
|
|
|
|
if (type !== 'string' && type !== 'list' && type !== 'number') {
|
|
|
|
return;
|
2022-08-04 13:34:30 +02:00
|
|
|
}
|
|
|
|
|
2022-08-24 10:38:08 +02:00
|
|
|
// If we're editing a feature strategy that has a newly added parameter,
|
|
|
|
// the value will be `undefined` until the field has been edited.
|
|
|
|
if (required && (typeof value === 'undefined' || value === '')) {
|
|
|
|
return 'Field is required';
|
2022-08-04 13:34:30 +02:00
|
|
|
}
|
2022-08-22 16:35:51 +02:00
|
|
|
|
2022-08-24 10:38:08 +02:00
|
|
|
if (type === 'number' && !isValidNumberOrEmpty(value)) {
|
|
|
|
return 'Not a valid number.';
|
2022-08-22 16:35:51 +02:00
|
|
|
}
|
2022-08-04 13:34:30 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
const isValidNumberOrEmpty = (value: string | number | undefined): boolean => {
|
2022-08-24 10:38:08 +02:00
|
|
|
return (
|
|
|
|
typeof value === 'undefined' ||
|
|
|
|
value === '' ||
|
|
|
|
/^\d+$/.test(String(value))
|
|
|
|
);
|
2022-08-22 16:35:51 +02:00
|
|
|
};
|