I have a form field that is conditionally required depending on another field's value. Using Form API:

          $form['details_' . $method['provider'] . '_' . $code]['lastname'] = array(
            '#type' => 'textfield',
            '#title' => t('Last Name'),
            '#disabled' => $disabled,
            '#states' => array(
              'visible' => array(':input[name="method"]' => array('value' => $code)),
              'required' => array(':input[name="method"]' => array('value' => $code))
            ),
          );

The field shows up as required, but somehow fails to respect clientside validation?

Comments

attiks’s picture

Clientside validation checks for '#required' on the item level, you could try the following

          $form['details_' . $method['provider'] . '_' . $code]['lastname'] = array(
            '#type' => 'textfield',
            '#title' => t('Last Name'),
            '#disabled' => $disabled,
            '#required' => TRUE,
            '#states' => array(
              'visible' => array(':input[name="method"]' => array('value' => $code)),
              'required' => array(':input[name="method"]' => array('value' => $code))
            ),
          );
Anonymous’s picture

Yeah that makes it conditional on the frontend, but always required on server-side.

attiks’s picture

To be sure, you enabled 'Clientside Validation States'?

Jelle_S’s picture

Status: Active » Postponed (maintainer needs more info)
haggins’s picture

Status: Postponed (maintainer needs more info) » Active

Same here. There's no clientside validation error but one from serverside after submitting the form. "Clientside Validation States" is enabled. The field is set #required and should only be required if the conditional requirements were hit.

Is a behavior like that the intention behind this submodule or does it affect only #rules validation by design?

leducvin’s picture

Version: 7.x-1.x-dev » 7.x-2.x-dev
Issue summary: View changes

Still a problem today in 7.x-2.x-dev. I am using hook_form_alter to set a conditional required state on a field:

$form['field_some_text_area']['#states'] = array(
    'required' => array(
        ':input[name="field_some_select_list[und]"]' => array('value' => '3'),
    ),
);

100 % of the rest of the form is validated client-side correctly. However when field_some_select_list has the value 3, a red asterisk shows up on form to indicate the field_some_text_area is required, as expected, but client-side validation doesn't happen.

Because I set a validation callback:

$form['actions']['submit']['#validate'][] = '_validate_my_form';

,upon form submission, the form is validated server-side. If I don't set the callback, them the field just goes unvalidated.

I have the clientside_validation_states module enabled.