UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

87 lines (86 loc) 3.09 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = require("react"); var _index = _interopRequireDefault(require("../String/index.js")); var _useTranslation = _interopRequireDefault(require("../../hooks/useTranslation.js")); var _withComponentMarkers = _interopRequireDefault(require("../../../../shared/helpers/withComponentMarkers.js")); var _jsxRuntime = require("react/jsx-runtime"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function OrganizationNumber(props) { const translations = (0, _useTranslation.default)().OrganizationNumber; const { errorOrgNo, errorOrgNoLength, errorRequired, label } = translations; const errorMessages = (0, _react.useMemo)(() => ({ 'Field.errorRequired': errorRequired, 'Field.errorPattern': errorOrgNo, ...props.errorMessages }), [errorRequired, errorOrgNo, props.errorMessages]); const organizationNumberValidator = (0, _react.useCallback)(value => { if (value !== undefined) { const orgNoIs9Digits = (value === null || value === void 0 ? void 0 : value.length) === 9; if (!orgNoIs9Digits) { return Error(errorOrgNoLength); } if (orgNoIs9Digits && !isValidOrgNumber(value)) { return Error(errorOrgNo); } } return undefined; }, [errorOrgNo, errorOrgNoLength]); const { validate = true, omitMask, onChangeValidator, onBlurValidator = organizationNumberValidator, label: labelProp, width } = props; const mask = (0, _react.useMemo)(() => omitMask ? [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] : [/\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/], [omitMask]); const onBlurValidatorToUse = onBlurValidator === false ? undefined : onBlurValidator; const StringFieldProps = { ...props, className: 'dnb-forms-field-organization-number', label: labelProp !== null && labelProp !== void 0 ? labelProp : label, errorMessages, mask, width: width !== null && width !== void 0 ? width : 'medium', inputMode: 'numeric', onChangeValidator: validate ? onChangeValidator : undefined, onBlurValidator: validate ? onBlurValidatorToUse : undefined, exportValidators: { organizationNumberValidator } }; return (0, _jsxRuntime.jsx)(_index.default, { ...StringFieldProps }); } function isValidOrgNumber(digits) { if (parseFloat(digits) === 0) { return false; } let checkDigit = 2; let sum = 0; for (let i = digits.length - 2; i >= 0; --i) { sum += parseInt(digits.charAt(i), 10) * checkDigit; checkDigit += 1; if (checkDigit > 7) { checkDigit = 2; } } const result = 11 - sum % 11; const finalCheckDigit = result === 11 ? 0 : result; return parseInt(digits.charAt(digits.length - 1), 10) === finalCheckDigit; } (0, _withComponentMarkers.default)(OrganizationNumber, { _supportsSpacingProps: true }); var _default = exports.default = OrganizationNumber; //# sourceMappingURL=OrganizationNumber.js.map