i have a form with two fields, FieldA (Select List) and FieldB (Select List, required field).

How to set the FieldB to optional when FieldA has certain value in order to pass the form validation?


First mark the field B as not required if you have set the field as required using UI

if field B is not set as required then you can continue with the following code.<br/>

For none value in field B we can set custom form error using form_set_error();

     function hook_form_alter($form, &$form_state, $form_id) {
        if ($form_id == 'abc') {
        $form['#validate'][] = 'hook_abc_validate'

       function hook_abc_validate($form, $form_state) {

        if ($form['field_A']['und']['0']['value'] == 'your_value') {

        $form['field_B']['#required'] = 0;
        else {
        $form['field_B']['#required'] = 1;

    if ($form['field_B']['und']['0']['value'] == '_none') {
            form_set_error('field_B', 'field_B cannot be none');
| improve this answer | |
  • when the field is not set as required, there is a -none- value in the top of the list, so the form always get validated even thought user input nothing. am i missing something? – Kent Nov 19 '13 at 12:29
  • check the edited answer – harshal Nov 19 '13 at 12:54
  • so this line does nothing right? $form['field_B']['#required'] = 1; i still have to validate it by myself. – Kent Nov 20 '13 at 6:45
  • the line $form['field_B']['#required'] = 1 makes this field_B required and select list will have value '_none' for that we need to use form_set_error .Do you get this let me know? – harshal Nov 20 '13 at 7:07
  • by setting $form['field_B']['#required'] = 1 in the function hook_abc_validate has no effect to the field, neither validation nor the '*' mark. i understand the form_set_error part. – Kent Nov 20 '13 at 7:47

Try using the #states attribute: a structured array describing the different JavaScript states that can be applied to the element when certain conditions are met. Please read the extensive description of this feature at drupal_process_states()

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.