com.vaadin.flow.component.datepicker.

Class DatePicker

All Implemented Interfaces:

AttachNotifier, BlurNotifier<DatePicker>, DetachNotifier, Focusable<DatePicker>, FocusNotifier<DatePicker>, HasAriaLabel, HasElement, HasEnabled, HasHelper, HasLabel, HasPlaceholder, HasSize, HasStyle, HasTheme, HasValidation, HasValue<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>, HasValueAndElement<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>, HasAllowedCharPattern, HasAutoOpen, HasClearButton, HasClientValidation, HasOverlayClassName, HasPrefix, HasThemeVariant<DatePickerVariant>, HasTooltip, HasValidationProperties, InputField<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>, HasValidator<LocalDate>, Serializable

@Tag("vaadin-date-picker") @NpmPackage(value="@vaadin/polymer-legacy-adapter",version="24.6.3") @NpmPackage(value="@vaadin/date-picker",version="24.6.3") @NpmPackage(value="date-fns",version="2.29.3") @JsModule("@vaadin/polymer-legacy-adapter/style-modules.js") @JsModule("@vaadin/date-picker/src/vaadin-date-picker.js") @JsModule("./datepickerConnector.js") public class DatePicker extends AbstractSinglePropertyField<DatePicker,LocalDate> implements Focusable<DatePicker>, HasAllowedCharPattern, HasAriaLabel, HasAutoOpen, HasClearButton, HasClientValidation, InputField<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>, HasOverlayClassName, HasPrefix, HasThemeVariant<DatePickerVariant>, HasValidationProperties, HasValidator<LocalDate>, HasPlaceholder

Date Picker is an input field that allows the user to enter a date by typing or by selecting from a calendar overlay.

DatePicker allows setting and getting LocalDate objects, setting minimum and maximum date ranges and has internationalization support by using the DatePicker.DatePickerI18n object.

This component allows the date to be entered directly using the keyboard in the format of the current locale or through the date picker overlay. The overlay opens when the field is clicked and/or any input is entered when the field is focused.

Validation

Date Picker comes with a built-in validation mechanism based on constraints. Validation is triggered whenever the user initiates a date change, for example by selection from the overlay or manual entry followed by Enter or blur. Programmatic value changes trigger validation as well.

Validation verifies that the value is parsable into LocalDate and satisfies the specified constraints. If validation fails, the component is marked as invalid and an error message is displayed below the input.

The following constraints are supported:

Error messages for unparsable input and constraints can be configured with the DatePicker.DatePickerI18n object, using the respective properties. If you want to provide a single catch-all error message, you can also use the setErrorMessage(String) method. Note that such an error message will take priority over i18n error messages if both are set.

In addition to validation, constraints may also have a visual aspect. For example, dates before the minimum date are displayed as disabled in the overlay to prevent their selection.

For more advanced validation that requires custom rules, you can use Binder. By default, before running custom validators, Binder will also check if the date is parsable and satisfies the component constraints, displaying error messages from the DatePicker.DatePickerI18n object. The exception is the required constraint, for which Binder provides its own API, see asRequired().

However, if Binder doesn't fit your needs and you want to implement fully custom validation logic, you can disable the constraint validation by setting setManualValidation(boolean) to true. This will allow you to control the invalid state and the error message manually using HasValidationProperties.setInvalid(boolean) and setErrorMessage(String) API.

Author:

Vaadin Ltd

See Also:

  • Constructor Details

  • Method Details

    • setErrorMessage

      public void setErrorMessage(String errorMessage)

      Sets a single error message to display for all constraint violations. The error message will only appear when the component is flagged as invalid, either as a result of constraint validation or by the developer through HasValidationProperties.setInvalid(boolean) if manual validation mode is enabled.

      Distinct error messages for unparsable input and different constraints can be configured with the DatePicker.DatePickerI18n object, using the respective properties. However, note that the error message set with setErrorMessage(String) will take priority and override any i18n error messages if both are set.

      Specified by:

      setErrorMessage in interface HasValidation

      Specified by:

      setErrorMessage in interface HasValidationProperties

      Parameters:

      errorMessage - the error message to set, or null to clear

    • setMin

      public void setMin(LocalDate min)

      Sets the minimum date allowed to be selected for this field. Dates before that will be disabled in the calendar overlay. Manual entry of such dates will cause the component to invalidate.

      The minimum date is inclusive.

      Parameters:

      min - the minimum date, or null to remove this constraint

      See Also:

    • getMin

      public LocalDate getMin()

      Gets the minimum date allowed to be selected for this field.

      Returns:

      the minimum date, or null if no minimum is set

      See Also:

    • setMax

      public void setMax(LocalDate max)

      Sets the maximum date allowed to be selected for this field. Dates after that will be disabled in the calendar overlay. Manual entry of such dates will cause the component to invalidate.

      The maximum date is inclusive.

      Parameters:

      max - the maximum date, or null to remove this constraint

      See Also:

    • getMax

      public LocalDate getMax()

      Gets the maximum date allowed to be selected for this field.

      Returns:

      the maximum date, or null if no maximum is set

      See Also:

    • setLocale

      public void setLocale(Locale locale)

      Set the Locale for the Date Picker. The displayed date will be matched to the format used in that locale.

      NOTE:Supported formats are MM/DD/YYYY, DD/MM/YYYY and YYYY/MM/DD. Browser compatibility can be different based on the browser and mobile devices, you can check here for more details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

      When using custom date formats through setI18n(DatePickerI18n), setting a locale has no effect, and dates will always be parsed and displayed using the custom date format.

      Parameters:

      locale - the locale set to the date picker, cannot be null

    • getLocale

      public Locale getLocale()

      Gets the Locale for this date picker

      Overrides:

      getLocale in class Component

      Returns:

      the locale used for this picker

    • setAriaLabel

      public void setAriaLabel(String ariaLabel)

      Description copied from interface: HasAriaLabel

      Set the aria-label of the component to the given text.

      This method should not be used if HasAriaLabel.setAriaLabelledBy(String) is also used. If both attributes are present, aria-labelledby will take precedence over aria-label.

      Specified by:

      setAriaLabel in interface HasAriaLabel

      Parameters:

      ariaLabel - the aria-label text to set or null to clear

    • getAriaLabel

      public Optional<String> getAriaLabel()

      Description copied from interface: HasAriaLabel

      Gets the aria-label of the component.

      Specified by:

      getAriaLabel in interface HasAriaLabel

      Returns:

      an optional aria-label of the component if no aria-label has been set

    • setAriaLabelledBy

      public void setAriaLabelledBy(String labelledBy)

      Description copied from interface: HasAriaLabel

      Set the aria-labelledby of the component. The value must be a valid id attribute of another element that labels the component. The label element must be in the same DOM scope of the component, otherwise screen readers may fail to announce the label content properly.

      This method should not be used if HasAriaLabel.setAriaLabel(String) is also used. If both attributes are present, aria-labelledby will take precedence over aria-label.

      Specified by:

      setAriaLabelledBy in interface HasAriaLabel

      Parameters:

      labelledBy - the string with the id of the element that will be used as label or null to clear

    • getAriaLabelledBy

      public Optional<String> getAriaLabelledBy()

      Description copied from interface: HasAriaLabel

      Gets the aria-labelledby of the component

      Specified by:

      getAriaLabelledBy in interface HasAriaLabel

      Returns:

      an optional aria-labelledby of the component if no aria-labelledby has been set

    • onAttach

      protected void onAttach(AttachEvent attachEvent)

      Description copied from class: Component

      Called when the component is attached to a UI.

      This method is invoked before the AttachEvent is fired for the component.

      Make sure to call super.onAttach when overriding this method.

      Overrides:

      onAttach in class Component

      Parameters:

      attachEvent - the attach event

    • getI18n

      public DatePicker.DatePickerI18n getI18n()

      Gets the internationalization object previously set for this component.

      NOTE: Updating the instance that is returned from this method will not update the component if not set again using setI18n(DatePickerI18n)

      Returns:

      the i18n object or null if no i18n object has been set

    • setI18n

      public void setI18n(DatePicker.DatePickerI18n i18n)

      Sets the internationalization object for this component.

      Parameters:

      i18n - the i18n object, not null

    • getDefaultValidator

      public Validator<LocalDate> getDefaultValidator()

      Description copied from interface: HasValidator

      Returns a validator that checks the state of the Value. This should be overridden for components with internal value conversion or validation, e.g. when the user is providing a string that has to be parsed into a date. An invalid input from user will be exposed to a Binder and can be seen as a validation failure.

      Specified by:

      getDefaultValidator in interface HasValidator<LocalDate>

      Returns:

      state validator

    • addValidationStatusChangeListener

      public Registration addValidationStatusChangeListener(ValidationStatusChangeListener<LocalDate> listener)

      Description copied from interface: HasValidator

      Enables the implementing components to notify changes in their validation status to the observers.

      Note: This method can be overridden by the implementing classes e.g. components, to enable the associated Binder.Binding instance subscribing for their validation change events and revalidate itself.

      This method primarily designed for notifying the Binding about the validation status changes of a bound component at the client-side. WebComponents such as <vaadin-date-picker> or any other component that accept a formatted text as input should be able to communicate their invalid status to their server-side instance, and a bound server-side component instance must notify its binding about this validation status change as well. When the binding instance revalidates, a chain of validators and convertors get executed one of which is the default validator provided by HasValidator.getDefaultValidator(). Thus, In order for the binding to be able to show/clear errors for its associated bound field, it is important that implementing components take that validation status into account while implementing any validator and converter including HasValidator.getDefaultValidator(). Here is an example:

       @Tag("date-picker-demo")
       public class DatePickerDemo implements HasValidator<LocalDate> {
      
           // Each web component has a way to communicate its validation status
           // to its server-side component instance. The following
           // clientSideValid state is introduced here just for the sake of
           // simplicity of this code snippet:
           boolean clientSideValid = true;
      
           /**
            * Note how clientSideValid engaged in the definition of
            * this method. It is important to reflect this status either in the
            * returning validation result of this method or any other validation
            * that is associated with this component.
           */
           @Override
           public Validator getDefaultValidator() {
               return (value, valueContext) -> clientSideValid
                       ? ValidationResult.ok()
                       : ValidationResult.error("Invalid date format");
           }
      
           private final Collection<ValidationStatusChangeListener<LocalDate>> validationStatusListeners = new ArrayList<>();
      
           /**
            * This enables the binding to subscribe for the validation status
            * change events that are fired by this component and revalidate
            * itself respectively.
           */
           @Override
           public Registration addValidationStatusChangeListener(
                   ValidationStatusChangeListener<LocalDate> listener) {
               validationStatusListeners.add(listener);
               return () -> validationStatusListeners.remove(listener);
           }
      
           private void fireValidationStatusChangeEvent(
                   boolean newValidationStatus) {
               if (this.clientSideValid != newValidationStatus) {
                   this.clientSideValid = newValidationStatus;
                   var event = new ValidationStatusChangeEvent<>(this,
                           newValidationStatus);
                   validationStatusListeners.forEach(
                           listener -> listener.validationStatusChanged(event));
               }
           }
       }
       

      Specified by:

      addValidationStatusChangeListener in interface HasValidator<LocalDate>

      Returns:

      Registration of the added listener.

      See Also:

    • isInputValuePresent

      protected boolean isInputValuePresent()

      Returns whether the input element has a value or not.

      Returns:

      true if the input element's value is populated, false otherwise

    • setFallbackParser

      public void setFallbackParser(SerializableFunction<String,Result<LocalDate>> fallbackParser)

      Sets a parser to handle user input that cannot be parsed using the i18n date formats.

      The parser is a function that receives the user-entered string and returns a Result with the parsed date or an error message. If the parser returns an error message, the field will be marked as invalid, displaying that message as a validation error.

      Example:

       datePicker.setFallbackParser(s -> {
           if (s.equals("tomorrow")) {
               return Result.ok(LocalDate.now().plusDays(1));
           } else {
               return Result.error("Invalid date format");
           }
       });
       

      NOTE: When a fallback parser is set, the i18n error message from DatePicker.DatePickerI18n.getBadInputErrorMessage() is not used.

      Parameters:

      fallbackParser - the parser function

    • getFallbackParser

      public SerializableFunction<String,Result<LocalDate>> getFallbackParser()

      Gets the parser that is used as a fallback when user input cannot be parsed using the i18n date formats.

      Returns:

      the parser function

    • setValue

      public void setValue(LocalDate value)

      Description copied from interface: HasValue

      Sets the value of this object. If the new value is not equal to getValue(), fires a value change event. May throw IllegalArgumentException if the value is not acceptable.

      Implementation note: the implementing class should document whether null values are accepted or not, and override HasValue.getEmptyValue() if the empty value is not null.

      Specified by:

      setValue in interface HasValue<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>

      Overrides:

      setValue in class AbstractField<DatePicker,LocalDate>

      Parameters:

      value - the new value

    • setModelValue

      protected void setModelValue(LocalDate newModelValue, boolean fromClient)

      Description copied from class: AbstractField

      Updates the model value if the value has actually changed. Subclasses should call this method whenever the user has changed the value. A value change event is fired if the new value is different from the previous value according to AbstractField.valueEquals(Object, Object).

      If the value is from the client-side and this field is in readonly mode, then the new model value will be ignored. AbstractField.setPresentationValue(Object) will be called with the previous model value so that the representation shown to the user can be reverted.

      See AbstractField for an overall description on the difference between model values and presentation values.

      Overrides:

      setModelValue in class AbstractField<DatePicker,LocalDate>

      Parameters:

      newModelValue - the new internal value to use

      fromClient - true if the new value originates from the client; otherwise false

    • setLabel

      public void setLabel(String label)

      Sets the label for the datepicker.

      Specified by:

      setLabel in interface HasLabel

      Parameters:

      label - value for the label property in the datepicker

    • getLabel

      public String getLabel()

      Gets the label of the datepicker.

      Specified by:

      getLabel in interface HasLabel

      Returns:

      the label property of the datePicker

    • setInitialPosition

      public void setInitialPosition(LocalDate initialPosition)

      Date which should be visible when there is no value selected.

      The same date formats as for the value property are supported.

      Parameters:

      initialPosition - the LocalDate value to set

    • getInitialPosition

      public LocalDate getInitialPosition()

      Get the visible date when there is no value selected.

      The same date formats as for the value property are supported.

      This property is not synchronized automatically from the client side, so the returned value may not be the same as in client side.

      Returns:

      the initialPosition property from the datepicker

    • setRequiredIndicatorVisible

      public void setRequiredIndicatorVisible(boolean required)

      Sets whether the user is required to provide a value. When required, an indicator appears next to the label and the field invalidates if the value is cleared.

      NOTE: The required indicator is only visible when the field has a label, see setLabel(String).

      Specified by:

      setRequiredIndicatorVisible in interface HasValue<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>

      Specified by:

      setRequiredIndicatorVisible in interface HasValueAndElement<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>

      Parameters:

      required - true to make the field required, false otherwise

      See Also:

    • isRequiredIndicatorVisible

      public boolean isRequiredIndicatorVisible()

      Gets whether the user is required to provide a value.

      Specified by:

      isRequiredIndicatorVisible in interface HasValue<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>

      Specified by:

      isRequiredIndicatorVisible in interface HasValueAndElement<AbstractField.ComponentValueChangeEvent<DatePicker,LocalDate>,LocalDate>

      Returns:

      true if the field is required, false otherwise

      See Also:

    • setRequired

      public void setRequired(boolean required)

      Alias for setRequiredIndicatorVisible(boolean).

      Parameters:

      required - true to make the field required, false otherwise

    • isRequired

      public boolean isRequired()

      Alias for isRequiredIndicatorVisible()

      Returns:

      true if the field is required, false otherwise

    • setWeekNumbersVisible

      public void setWeekNumbersVisible(boolean weekNumbersVisible)

      Set the week number visible in the DatePicker.

      Set true to display ISO-8601 week numbers in the calendar.

      Notice that displaying week numbers is only supported when i18n.firstDayOfWeek is 1 (Monday).

      Parameters:

      weekNumbersVisible - the boolean value to set

    • isWeekNumbersVisible

      public boolean isWeekNumbersVisible()

      Get the state of showWeekNumbers property of the datepicker

      This property is not synchronized automatically from the client side, so the returned value may not be the same as in client side.

      Returns:

      the showWeekNumbers property from the datepicker

    • setOpened

      public void setOpened(boolean opened)

      Sets the opened property of the datepicker to open or close its overlay.

      Parameters:

      opened - true to open the datepicker overlay, false to close it

    • open

      public void open()

      Opens the datepicker overlay.

    • close

      protected void close()

      Closes the datepicker overlay.

    • isOpened

      @Synchronize(property="opened", value="opened-changed") public boolean isOpened()

      Gets the states of the drop-down for the datepicker

      This property is synchronized automatically from client side when an opened-changed event happens.

      Returns:

      true if the drop-down is opened, false otherwise

    • setName

      public void setName(String name)

      Sets the name of the DatePicker.

      Parameters:

      name - the string value to set

    • getName

      public String getName()

      Gets the name of the DatePicker.

      Returns:

      the name property from the DatePicker

    • setManualValidation

      public void setManualValidation(boolean enabled)

      Description copied from interface: HasValidation

      Sets whether manual validation mode is enabled for the component.

      When enabled, the component doesn't perform its built-in constraint validation on value change, blur, and other events. This allows manually controlling the invalid state and error messages using the HasValidation.setInvalid(boolean) and HasValidation.setErrorMessage(String) methods. Manual mode is helpful when there is a need for a totally custom validation logic that cannot be achieved with Binder.

      Example:

       Field field = new Field();
       field.setManualValidation(true);
       field.addValueChangeListener(event -> {
           if (Objects.equal(event.getValue(), "")) {
               field.setInvalid(true);
               field.setErrorMessage("The field is required.");
           } else {
               field.setInvalid(false);
           }
       });
       

      For components that don't have built-in validation, the method has no effect.

      Specified by:

      setManualValidation in interface HasValidation

      Parameters:

      enabled - whether to enable manual validation mode.

    • validate

      protected void validate()

      Validates the current value against the constraints and sets the invalid property and the errorMessage property based on the result. If a custom error message is provided with setErrorMessage(String), it is used. Otherwise, the error message defined in the i18n object is used.

      The method does nothing if the manual validation mode is enabled.

    • addOpenedChangeListener

      public Registration addOpenedChangeListener(ComponentEventListener<DatePicker.OpenedChangeEvent> listener)

      Adds a listener for opened-changed events fired by the webcomponent.

      Parameters:

      listener - the listener

      Returns:

      a Registration for removing the event listener

    • addInvalidChangeListener

      public Registration addInvalidChangeListener(ComponentEventListener<DatePicker.InvalidChangeEvent> listener)

      Adds a listener for invalid-changed events fired by the webcomponent.

      Parameters:

      listener - the listener

      Returns:

      a Registration for removing the event listener