Skip to main content

InputField

A configurable InputField component used to gather user input through a text field.

Import

// with @dhl-official/react-library:
import { DhlInputField } from "@dhl-official/react-library"
// with @dhl-official/ui-libraries/react-library:
import { DhlInputField } from "@dhl-official/ui-libraries/react-library"

Code​

<DhlInputField
variant={{
label: 'Label',
placeholder: 'Placeholder',
}}
></DhlInputField>

Payment method mark​

Set leftPaymentIcon to show a payment method mark ahead of the value, for example on a card number field. Marks come from the payments export of @dhl-official/icons and keep their brand colours. Setting the prop is what shows the mark, there is no separate toggle. The field takes care of vertical centring and of the spacing between the mark and the value in every size variant.

import { payments } from "@dhl-official/icons";

<duil310-dhl-input-field
variant={{ label: "Card number" }}
leftPaymentIcon={payments.visa}
></duil310-dhl-input-field>

The mark is decorative by default, since the detected method is normally already named by the value or the label. When it is the only thing identifying the method, describe it with leftPaymentIconAlt, which puts the mark back into the accessibility tree:

<duil310-dhl-input-field
variant={{ label: "Card number" }}
leftPaymentIcon={payments.visa}
leftPaymentIconAlt="Visa payment method"
></duil310-dhl-input-field>

Interactive Demo​

Examples with prefix / suffix addon​

Example 1​

Addon type: "prefix"


Code example
<DhlInputField
variant={{
label: "Label",
placeholder: "Placeholder",
}}
addon={{
type: "prefix",
label: "Unit"
}}
/>

Example 2​

Addon type: "suffix" with options, colorVariant: "gray", validation type: "valid"


Code example
<DhlInputField
variant={{
label: "Label",
placeholder: "Placeholder",
}}
addon={{
type: "suffix",
label: "Unit",
colorVariant: ColorVariants.gray
}}
validation={{
type: "valid",
message: "Validation message"
}}
/>

Example 3​

Addon type: "prefix" with options


Code example
<DhlInputField
variant={{
label: "Label",
placeholder: "Placeholder",
}}
addon={{
type: "prefix",
label: "Unit",
colorVariant: ColorVariants.white,
options: [
{
label: "g",
value: "g"
},
{
label: "kg",
value: "kg"
},
{
label: "oz",
value: "oz"
},
{
label: "lb",
value: "lb"
},
],
}}
/>

Example 4​

Addon type: "suffix" with options, colorVariant: "gray", validation type: "invalid"


Code example
<DhlInputField
variant={{
label: "Label",
placeholder: "Placeholder",
}}
addon={{
type: "suffix",
label: "Unit",
colorVariant: ColorVariants.gray,
options: [
{
label: "g",
value: "g"
},
{
label: "kg",
value: "kg"
},
{
label: "oz",
value: "oz"
},
{
label: "lb",
value: "lb"
},
],
}}
validation={{
type: "invalid",
message: "Validation message"
}}
/>

Examples with Number Input Validation​

info

The maxDigits and decimalPoint props only work when type="number". These props are designed specifically for numeric input validation and will have no effect on other input types.

Example: Limiting Integer Digits​

Using maxDigits to limit the number of digits before the decimal point (e.g., max 5 digits):


Code example
<DhlInputField
type="number"
maxDigits={5}
variant={{
label: "Amount (Max 5 digits)",
placeholder: "Enter amount",
}}
/>

Example: Limiting Decimal Places​

Using decimalPoint to limit decimal places (e.g., 2 decimal places for currency):


Code example
<DhlInputField
type="number"
decimalPoint={2}
variant={{
label: "Price (2 decimals)",
placeholder: "Enter price",
}}
/>

Example: Combining Both Validations​

Combining maxDigits and decimalPoint for precise control (e.g., max 6 digits, 2 decimals):


Code example
<DhlInputField
type="number"
maxDigits={6}
decimalPoint={2}
variant={{
label: "Price (Max 6 digits, 2 decimals)",
placeholder: "Enter price",
}}
/>

Example: Block Decimals Entirely​

Using decimalPoint={0} to prevent decimal input (integers only):


Code example
<DhlInputField
type="number"
decimalPoint={0}
variant={{
label: "Quantity (Integers only)",
placeholder: "Enter quantity",
}}
/>

Decimal Separator Configuration​

When using type="number" with decimal values, you can configure the decimal separator using the decimalSeparator prop. This is useful for accommodating different locale preferences (e.g., European format uses comma, US format uses dot).

European Format (Comma Separator)​


Code example
<DhlInputField
type="number"
decimalPoint={2}
decimalSeparator=","
variant={{
label: "Price (EUR)",
placeholder: "e.g., 123,45",
}}
/>

US Format (Dot Separator)​


Code example
<DhlInputField
type="number"
decimalPoint={2}
decimalSeparator="."
variant={{
label: "Price (USD)",
placeholder: "e.g., 123.45",
}}
/>

Key Features:

  • When decimalSeparator is set, the input automatically uses type="text" internally to avoid browser validation issues
  • Users can type either comma or dot, and the value is automatically normalized to the configured separator
  • The normalized value is what gets submitted with the form
  • Works together with decimalPoint and maxDigits props to limit decimal places and integer digits

Readme​

Usage​

Dhl-input-field​

Snippets of code in HTML and JavaScript to show some of the use cases for the component. The code is not meant to be executed, but to be used as a reference for the usage of the component.
Angular, React and Vue usages are not included in this documentation, but can be easily derived from the html and javascript code.

addon menu list position​

When the input has an addon with options, use menuListPosition to control where that list opens. Its default value, auto, chooses below or above from the available viewport space. Set it to below or above to keep the list fixed in that position.

<duil310-dhl-input-field has-dynamic-position="below"></duil310-dhl-input-field>

default usage​

variant.label is required. variant.placeholder is optional. variant.type was removed because animated behavior of label and placeholder is no longer supported. When placeholder is not provided, then label stays permanently animated.

<form novalidate>
<duil310-dhl-input-field name="duil310-dhl-input-field-custom-element"></duil310-dhl-input-field>
<duil310-dhl-button
type="reset"
variant="outline"
>reset</duil310-dhl-button
>
<duil310-dhl-button type="submit">submit</duil310-dhl-button>
</form>

<script type="module">
const form = document.querySelector("form");
const input = document.querySelector("duil310-dhl-input-field");

input.variant = {
label: "Label",
placeholder: "Placeholder",
};

form.addEventListener("submit", async (e) => {
e.preventDefault();
console.log(Object.fromEntries(new FormData(form)));
return await form.checkValidity();
});
</script>

usage with validation (required) and (browser) default validation message​

<form novalidate>
<duil310-dhl-input-field
name="duil310-dhl-input-field-custom-element"
required
>
</duil310-dhl-input-field>
<duil310-dhl-button
type="reset"
variant="outline"
>reset</duil310-dhl-button
>
<duil310-dhl-button type="submit">submit</duil310-dhl-button>
</form>

<script type="module">
const form = document.querySelector("form");
const input = document.querySelector("duil310-dhl-input-field");

input.variant = {
label: "Label",
placeholder: "Placeholder",
};

form.addEventListener("submit", async (e) => {
e.preventDefault();
console.log(Object.fromEntries(new FormData(form)));
return await form.checkValidity();
});
</script>

usage with validation (required) and custom validation message​

<form novalidate>
<duil310-dhl-input-field
name="duil310-dhl-input-field-custom-element"
required
>
</duil310-dhl-input-field>
<duil310-dhl-button
type="reset"
variant="outline"
>reset</duil310-dhl-button
>
<duil310-dhl-button type="submit">submit</duil310-dhl-button>
</form>

<script type="module">
const form = document.querySelector("form");
const input = document.querySelector("duil310-dhl-input-field");

input.variant = {
label: "Label",
placeholder: "Placeholder",
};

const validationMessageInvalid = "This field is invalid";
const validationMessageValid = "This field valid";

form.addEventListener("submit", async (e) => {
const isValid = await e.target.checkValidity();
if (isValid) {
input.validation = {
type: "valid",
message: validationMessageValid,
};
} else {
input.validation = {
type: "invalid",
message: validationMessageInvalid,
};
}
return isValid;
});
</script>

usage with tooltip​

The tooltip prop attaches a popover to the right icon. On mobile viewports (< 768 px) set isMobileVariant: true to anchor the tooltip below the input so it does not obscure the label or keyboard. The component automatically flips the tooltip back above the input when there is insufficient space below.

<duil310-dhl-input-field id="input-tooltip"></duil310-dhl-input-field>

<script type="module">
const input = document.querySelector("#input-tooltip");

input.variant = { label: "Shipment weight (kg)" };
input.rightIcon = "path/to/info-icon.svg";
input.tooltip = {
title: "Weight guidelines",
description: "Maximum weight per parcel is 31.5 kg for standard domestic shipments.",
placement: "top",
isMobileVariant: true,
};
</script>

usage with custom events​

<form novalidate>
<duil310-dhl-input-field
name="duil310-dhl-input-field-custom-element"
required
>
</duil310-dhl-input-field>
<duil310-dhl-button
type="reset"
variant="outline"
>reset</duil310-dhl-button
>
<duil310-dhl-button type="submit">submit</duil310-dhl-button>
<duil310-dhl-text></duil310-dhl-text>
</form>

<script type="module">
const form = document.querySelector("form");
const input = document.querySelector("duil310-dhl-input-field");
const text = document.querySelector("duil310-dhl-text");

input.variant = {
label: "Label",
placeholder: "Placeholder",
};

const validationMessageInvalid = "This field is invalid";
const validationMessageValid = "This field valid";

input.addEventListener("dhlBlur", async (e) => {
const isValid = await e.target.checkValidity();
if (isValid) {
input.validation = {
type: "valid",
message: validationMessageValid,
};
} else {
input.validation = {
type: "invalid",
message: validationMessageInvalid,
};
}
});

input.addEventListener("dhlChange", async (e) => {
text.innerHTML = e.target.value;
});

form.addEventListener("submit", async (e) => {
e.preventDefault();
console.log(Object.fromEntries(new FormData(form)));
return await form.checkValidity();
});
</script>

Properties​

PropertyAttributeDescriptionTypeDefault
addonaddonAn optional prop for the component to display prefix or suffix addon.{ type: "prefix" | "suffix"; label: string; colorVariant?: "gray" | "white"; leftIcon?: string; rightIcon?: string; clickEvent?: () => void; options?: DhlSelectionOptionType[]; optionClickEvent?: (o: DhlSelectionOptionType) => void; value?: string; }undefined
autoCompleteauto-completeAn optional prop used to set the autocomplete value. It takes any valid value that can be used for the autocomplete attribute of an HTMLInputElement.stringundefined
blurEventblur-event[DEPRECATED] Use dhlBlur event instead.

An optional onBlur callback handler.
(event: FocusEvent) => voidundefined
dataAriaActivedescendantdata-aria-activedescendantAn optional prop used to identify the currently active element within a composite widget context.stringundefined
dataAriaAutoCompletedata-aria-auto-completeAn optional prop used to indicate whether inputting text could trigger display of one or more predictions of the user's intended value.stringundefined
dataAriaDescribedbydata-aria-describedbyAn optional prop defining the list of reference IDs (separated by spaces), recommended when you want to an error message on your field.stringundefined
dataAriaExpandeddata-aria-expandedAn optional prop used for assistive technology support - used to mark expandable and collapsible regions.stringundefined
dataAriaHasPopupdata-aria-has-popupAn optional prop that lets the screen reader know that this component has a popup.stringundefined
dataAriaLabeldata-aria-labelAn optional prop defining the text read by the screen reader to represent the component; use this if you need different text to be read from label.stringundefined
dataAriaOwnsdata-aria-ownsAn optional attribute to identify an element (or elements) to define a visual, functional, or contextual relationship between a parent and it's child when it otherwise cannot be in the DOM hierarchy.stringundefined
dataClassNamedata-class-nameAn optional class name prop for the component.stringundefined
dataIddata-idAn optional prop. Gives a valid HTML ID attribute value for the component.string`duil310-dhl-input-field-${getRandomString()}`
dataMaskPiidata-mask-piiAn optional prop to mask sensitive data in session-replay tools. When true, sets data-di-mask on the inner element.booleanundefined
dataRoledata-roleAn optional prop defining the role attribute of the component.stringundefined
dataTestiddata-testidAn optional prop. The test id attached to the component as a data-testid attribute.stringundefined
dataTrackingdata-trackingAn optional data tracking prop for the component.stringundefined
decimalPointdecimal-pointAn optional prop to limit the number of decimal places allowed. Set to 0 to block decimals entirely, or a positive number to limit decimal places.numberundefined
decimalSeparatordecimal-separatorAn optional prop to define the decimal separator character. It accepts "," (comma) or "." (dot). When set, the input type becomes "text" to avoid browser validation issues, and all decimal values are automatically formatted to use the configured separator. Only applies when type="number"."," | "."undefined
disableValidationdisable-validationAn optional prop to disable the validation's visual feedback. Validation is still applied and validity state is still set to the form element.booleanfalse
focusEventfocus-event[DEPRECATED] Use dhlFocus event instead.

An optional onFocus callback handler.
(event: FocusEvent) => voidundefined
formNoValidateform-no-validateAn optional prop used to set native formnovalidate attribute. This bypasses form control validation for form submission for the types image and submit.booleanundefined
handleInputClearhandle-input-clearAn optional handleInputClear callback handler.(e: Event) => voidundefined
inputEventinput-event[DEPRECATED] Use dhlInput event instead.

An optional onInput callback handler.
(event: InputEvent) => voidundefined
isDisableddisabledAn optional flag to define if the component is disabled.booleanfalse
keyDownEventkey-down-event[DEPRECATED] Use dhlKeyDown event instead.

An optional onKeyDown callback handler.
(event: KeyboardEvent) => voidundefined
leftIconleft-iconAn optional prop to define left icon.stringundefined
leftImageleft-imageAn optional prop to define left image under input label.stringundefined
leftPaymentIconleft-payment-iconAn optional prop to define a payment method mark shown ahead of the input value, e.g. payments.visa from @dhl-official/icons. Setting it is what shows the mark, no separate toggle is needed.stringundefined
leftPaymentIconAltleft-payment-icon-altAn optional prop to define the alternative text of leftPaymentIcon, e.g. "Visa payment method". Leave it unset when the payment method is already named by the input value or label, so the mark stays decorative.string""
listlistAn optional attribute that specifies a datalist for the input field.stringundefined
loadingloadingAn optional prop that displays a neutral loader while asynchronous work is in progress. The input remains interactive.booleanfalse
maxmaxAn optional prop describing the maximum value that can be entered in the input field. Only works with type="number".stringundefined
maxDigitsmax-digitsAn optional prop to limit the number of digits allowed before the decimal point. Only works with type="number".numberundefined
menuListPositionmenu-list-positionAn optional prop controlling the addon menu list position. auto (the default) chooses above or below based on available viewport space; below and above keep the list fixed in the selected position."above" | "auto" | "below"MENU_LIST_POSITION.AUTO
minminAn optional prop describing the minimum value that can be entered in the input field. Only works with type="number".stringundefined
namenameAn optional value to be set to the element HTML name attribute. It takes any valid value that can be used for the name attribute of an HTMLInputElement.stringundefined
patternpatternAn optional prop describing the regular expression pattern that the input value must match.stringundefined
readonlyreadonlyAn optional prop to flag the component as readonly within a form context.booleanfalse
requiredrequiredAn optional prop to flag the component as required within a form context.booleanundefined
rightIconright-iconAn optional prop to define right icon.stringundefined
rightIconClickEventright-icon-click-eventAn optional right icon click callback handler.(e: Event) => voidundefined
rightIconColorVariantright-icon-color-variantAn optional prop to define right icon color variant."error" | "inverted" | "note" | "primary" | "secondary" | "success" | "sustainability" | "warning"undefined
showClearButtonshow-clear-buttonAn optional prop flag to define if clear button is displayedbooleantrue
sizesizeAn optional size prop for the component."md" | "sm"Sizes.MD
stepstepAn optional prop describing the step value for the input field. It works with type="number".stringundefined
tooltiptooltipAn optional prop to display tooltip on right icon hover.{ title: string; description: string; placement?: "top" | "bottom" | "left" | "right" | "none"; isMobileVariant?: boolean; }undefined
tooltipInlineModetooltip-inline-modeAn optional prop flag. When true, the tooltip info icon is rendered inline (next to the right icon / clear button) instead of on right-icon hover. Used by wrapper components like dhl-select, dhl-dropdown, duil310-dhl-country-select and duil310-dhl-autocomplete-field.booleanundefined
typetypeAn optional prop describing the type of the component. It takes any valid value that can be used for the type attribute of an HTMLInputElement.string"text"
validationvalidationAn optional object to set-up a custom components validation state. Required Fields: type{ type: "warning" | "valid" | "invalid" | "note"; message?: string; }undefined
valuevalueAn optional prop defining the value of the component which is taken when a form is submitted.string""
variant (required)variantA REQUIRED object to set-up a custom components variant state. It can be used to set a custom label and a custom placeholder text. label is required. placeholder is optional. type property was removed because animated behavior of label and placeholder is no longer supported. When placeholder is not provided, then label stays permanently animated.{ label: string; placeholder?: string; }undefined

Events​

EventDescriptionType
dhlBlurEvent emitted when the input field loses focus.CustomEvent<{ value: string; }>
dhlChangeEvent emitted when the input field changes value.CustomEvent<{ value: string; }>
dhlFocusEvent emitted when the input field receives focus.CustomEvent<{ value: string; }>
dhlInputEvent emitted when the input value changes.CustomEvent<{ value: string; }>
dhlKeyDownEvent emitted when a key is pressed down on the input field.CustomEvent<KeyboardEvent>
dhlKeyUpEvent emitted when a key is released on the input field.CustomEvent<KeyboardEvent>

Methods​

checkValidity() => Promise<boolean>​

Checks the validity of the input field.

Returns​

Type: Promise<boolean>

A promise that resolves to true if the input field is valid, otherwise false.

getInputElement() => Promise<HTMLInputElement>​

Retrieves the input element asynchronously.

Returns​

Type: Promise<HTMLInputElement>

A promise that resolves to the input element.

getValidationMessage() => Promise<string>​

Retrieves the validation message for the input field.

Returns​

Type: Promise<string>

A promise that resolves to a string representing the validation message.

reportValidity() => Promise<boolean>​

Reports the validity of the input field.

Returns​

Type: Promise<boolean>

A promise that resolves to a boolean indicating whether the input field is valid.

setValidity(validity: ValidityState, validationMessage?: string) => Promise<void>​

Sets the validity state of the input field.

Parameters​

NameTypeDescription
validityValidityState- The validity state to set.
validationMessagestring- An optional validation message to set.

Returns​

Type: Promise<void>

A Promise that resolves when the validity state is set.

willValidate() => Promise<boolean>​

Returns a promise that resolves to true if the element will successfully validate, or false otherwise.

Returns​

Type: Promise<boolean>

A promise that resolves to a boolean value indicating whether the element will validate.

Slots​

SlotDescription
"right-icon"slot intended for a DhlIcon to be displayed within DhlInputField

Dependencies​

Used by​

Depends on​

Graph​


Built by DHL User Interface Library Team!

Migrating from DUIL 1.0​

  • Rename onBlur to blurEvent
  • Rename disabled to isDisabled
  • Rename onChange to inputEvent
  • rightIcon now supplied via slot name right-icon
  • Remove prop ariaExpanded
  • Remove isBlock
  • Add formnovalidate
  • Add dataAriaActivedescendant
  • Add dataAriaAutoComplete
  • Add dataAriaExpanded
  • Add autoComplete
  • Add dataAriaOwns
  • Add focusEvent
  • Add keyDownEvent
  • Add dataRole