#states required is not working in form API

Created on 23 February 2017, over 7 years ago
Updated 2 February 2023, over 1 year ago

Hi There,

I want to use dependant text field with checkbox in drupal form.

I am using form #states with required, but form gets submitted without validating the text field.

Please check below code.

$form['dummy_checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dummy Checkbox'),
  );

  $form['dummy_checkbox_value'] = array(
    '#type' => 'textfield',
    '#title' => t('Dummy Checkbox Value'),
    '#states' => array(
      'visible' => array(
        ':input[name="dummy_checkbox"]' => array('checked' => TRUE)
      ),
      'required' => array(
        ':input[name="dummy_checkbox"]' => array('checked' => TRUE)
      ),
    )
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

Note : I have option to write validate function, but my checkbox and text field are multiple. So I need to work with #states only.

💬 Support request
Status

Closed: works as designed

Version

8.9 ⚰️

Component
Form 

Last updated about 11 hours ago

Created by

🇮🇳India virajrajankar Pune

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇺🇸United States maskedjellybean Portland, OR

    If anyone else is still looking for a solution to this, there seems to be some progress on this issue marked as related: https://www.drupal.org/project/drupal/issues/2912092 🐛 State required asterisk doesn't show Needs work

    Required state is still quite broken with this combination:
    Drupal 9.4.10
    Claro
    A Number (integer) field that should be required when a Boolean field is checked.

    My guess is that this depends on the theme, which explains why some people say it works.

Production build 0.69.0 2024