Files
pedwfrontend/components/elements/fields/decimalField.js

107 lines
3.4 KiB
JavaScript

import React from "react";
import _ from "lodash";
import useTranslation from "next-translate/useTranslation";
import { Field } from "redux-form";
import { RenderTextfield } from "./renderTextfield";
import { RenderDecimalField } from "./renderDecimalField";
import { validateField } from "../validationUtils";
const isVisibleByInclusion = ({
parentField,
form,
formProps,
parentFieldShowOnValue
}) =>
parentField != false &&
!_.isEmpty(formProps[form]) &&
_.has(formProps[form].values, parentField) &&
parentFieldShowOnValue.indexOf(
formProps[form].values[parentField].toString()
) > -1;
export function DecimalField(props) {
const {
name,
validation,
form,
formProps,
parentFieldShowOnValue,
parentField
} = props;
let { t } = useTranslation();
const showIfHasParentShowValue = isVisibleByInclusion({
parentField,
form,
formProps,
parentFieldShowOnValue
});
const validateDecimal = (value) => {
if (!value) return t("newappeal:is-required-label");
const regex = /^\d{1,6}(\.\d{1,2})?$/;
if (!regex.test(value)) {
return t("newappeal:invalid-decimal-label");
}
return undefined;
};
const requiredMessage = t("newappeal:is-required-label");
const emojiNotAllowedMessage = t("newappeal:emojis-not-allowed-label");
const invalidPostcodeMessage = t("newappeal:invalid-postcode-label");
return (
<>
{parentField != false ? (
showIfHasParentShowValue && (
<div className="govuk-form-group">
<Field
name={props.name}
id={props.name}
type="number"
className="govuk-input govuk-input--width-10"
spellCheck="false"
aria-describedby={name}
pattern="[0-9]*"
inputMode="numeric"
parse={Number}
validate={(value) =>
validateField(
value,
validation,
requiredMessage,
emojiNotAllowedMessage,
invalidPostcodeMessage
)
}
component={RenderTextfield}
label={props.label}
maxFieldLength={props.maxFieldLength}
/>
</div>
)
) : (
<div className="govuk-form-group">
<Field
name={props.name}
id={props.name}
type="text"
className="govuk-input govuk-input--width-10"
spellCheck="false"
aria-describedby={name}
pattern="^\d*\.?\d+$"
validate={[validateDecimal]}
component={RenderDecimalField}
label={props.label}
maxFieldLength={props.maxFieldLength}
/>
</div>
)}
</>
);
}