Class Switch

All Implemented Interfaces:
AttachNotifier, BlurNotifier<Switch>, ClickNotifier<Switch>, DetachNotifier, Focusable<Switch>, FocusNotifier<Switch>, HasAriaDescription, HasAriaLabel, HasElement, HasEnabled, HasHelper, HasLabel, HasSize, HasStyle, HasTheme, HasValidation, HasValue<AbstractField.ComponentValueChangeEvent<Switch,Boolean>,Boolean>, HasValueAndElement<AbstractField.ComponentValueChangeEvent<Switch,Boolean>,Boolean>, HasThemeVariant<SwitchVariant>, HasTooltip, HasValidationProperties, InputField<AbstractField.ComponentValueChangeEvent<Switch,Boolean>,Boolean>, HasValidator<Boolean>, Serializable

Switch is an input field representing a binary on/off choice.

This component is experimental and needs to be enabled with the com.vaadin.experimental.switchComponent feature flag.

Switch is functionally equivalent to Checkbox, but it is presented as an on/off toggle and is intended for a single setting that takes effect immediately. Unlike Checkbox, Switch has no indeterminate state.

Validation

Switch comes with a built-in validation mechanism that verifies that the field is selected when required is enabled.

Validation is triggered whenever the user toggles the switch. Programmatic toggling triggers validation as well. If validation fails, the component is marked as invalid and an error message is displayed below the input.

The required error message can be configured using either Switch.SwitchI18n.setRequiredErrorMessage(String) or HasValidationProperties.setErrorMessage(String).

For more advanced validation that requires custom rules, you can use Binder. Please note that Binder provides its own API for the required validation, see asRequired().

However, if Binder doesn't fit your needs and you want to implement fully custom validation logic, you can disable the built-in 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 HasValidationProperties.setErrorMessage(String) API.

Since:
25.3
Author:
Vaadin Ltd
See Also:
  • Constructor Details

  • Method Details

    • 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
    • setRequiredIndicatorVisible

      public void setRequiredIndicatorVisible(boolean required)
      Sets whether the user is required to switch on the control. When required, an indicator appears next to the label and the field invalidates if the switch is first turned on and then turned off.

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

      Specified by:
      setRequiredIndicatorVisible in interface HasValue<AbstractField.ComponentValueChangeEvent<Switch,Boolean>,Boolean>
      Specified by:
      setRequiredIndicatorVisible in interface HasValueAndElement<AbstractField.ComponentValueChangeEvent<Switch,Boolean>,Boolean>
      Parameters:
      required - true to make the field required, false otherwise
      See Also:
    • isRequiredIndicatorVisible

      public boolean isRequiredIndicatorVisible()
      Gets whether the user is required to switch on the control.
      Specified by:
      isRequiredIndicatorVisible in interface HasValue<AbstractField.ComponentValueChangeEvent<Switch,Boolean>,Boolean>
      Specified by:
      isRequiredIndicatorVisible in interface HasValueAndElement<AbstractField.ComponentValueChangeEvent<Switch,Boolean>,Boolean>
      Returns:
      true if the field is required, false otherwise
      See Also:
    • getLabel

      public String getLabel()
      Get the current label text.
      Specified by:
      getLabel in interface HasLabel
      Returns:
      the current label text
    • setLabel

      public void setLabel(String label)
      Set the current label text of this switch.
      Specified by:
      setLabel in interface HasLabel
      Parameters:
      label - the label text to set
    • setLabelComponent

      public void setLabelComponent(Component component)
      Replaces the label content with the given label component.
      Parameters:
      component - the component to be added to the label.
    • 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 ariaLabelledBy)
      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:
      ariaLabelledBy - 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
    • setAriaDescribedBy

      public void setAriaDescribedBy(String ariaDescribedBy)
      Sets the aria-describedby attribute of the component to one or more element IDs, separated by spaces.

      Each ID must match the id attribute of another element that describes the component. The description elements must be in the same DOM scope as the component, otherwise screen readers will fail to announce the description content properly.

      The referenced elements are announced in addition to the helper text and the error message.

      Specified by:
      setAriaDescribedBy in interface HasAriaDescription
      Parameters:
      ariaDescribedBy - a space-separated list of element IDs, or null to remove the attribute
      See Also:
    • getAriaDescribedBy

      public Optional<String> getAriaDescribedBy()
      Description copied from interface: HasAriaDescription
      Gets the aria-describedby attribute of the component.
      Specified by:
      getAriaDescribedBy in interface HasAriaDescription
      Returns:
      an optional aria-describedby, or an empty optional if none has been set
    • setAutofocus

      public void setAutofocus(boolean autofocus)
      Set the switch to be input focused when the page loads.
      Parameters:
      autofocus - the boolean value to set
    • isAutofocus

      public boolean isAutofocus()
      Get the state for the auto-focus property of the switch.
      Returns:
      the autofocus property from the switch
    • 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.
    • getDefaultValidator

      public Validator<Boolean> 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<Boolean>
      Returns:
      state validator
    • 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 HasValidationProperties.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.

    • getI18n

      public Switch.SwitchI18n 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(SwitchI18n)

      Returns:
      the i18n object or null if no i18n object has been set
    • setI18n

      public void setI18n(Switch.SwitchI18n i18n)
      Sets the internationalization object for this component.
      Parameters:
      i18n - the i18n object, not null