Files
pedwfrontend/components/elements/fields/numericField.js
T
2026-06-29 13:08:06 +00:00

115 lines
3.7 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 { validateField } from "../validationUtils";
import { hasOwn } from "../../utils";
const isVisibleByInclusion = ({
parentField,
form,
formProps,
parentFieldShowOnValue
}) =>
parentField != false &&
!_.isEmpty(formProps[form]) &&
hasOwn(formProps[form].values, parentField) &&
parentFieldShowOnValue.indexOf(
formProps[form].values[parentField].toString()
) > -1;
export function NumericField(props) {
const {
name,
label,
validation,
form,
formProps,
parentFieldShowOnValue,
parentField
} = props;
let { t } = useTranslation();
const required = (value) => {
return value || value == 0
? undefined
: t("newappeal:is-required-label");
};
const isNumber = (value) => {
const regex = /^\d+$/;
return regex.test(value)
? undefined
: t("newappeal:invalid-number-label");
};
const maxLength = (max) => (value) =>
value && value.length > max
? `Must be ${max} characters or less`
: undefined;
const showIfHasParentShowValue = isVisibleByInclusion({
parentField,
form,
formProps,
parentFieldShowOnValue
});
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-20"
spellCheck="false"
aria-describedby={name}
pattern="[0-9]*"
inputMode="numeric"
parse={Number}
validate={(value) =>
validateField(
value,
validation,
requiredMessage,
emojiNotAllowedMessage,
invalidPostcodeMessage
)
}
component={RenderTextfield}
label={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"
aria-describedby={name}
pattern="[0-9]*"
validate={[
required,
isNumber,
maxLength(props.maxFieldLength)
]}
component={RenderTextfield}
label={props.label}
maxFieldLength={props.maxFieldLength}
/>
</div>
)}
</>
);
}