Custom field validation condition not working I have created a custom form validation.

I am using webform module to build the form.

in _achva_tz_validate function there are two fields that have the same validation.

The second field, zug_id, is shown only if the user selects family_state  value to 1. if family_state is not 1 the zug_id field is hidden.

The issue is that the zug_id validation is not fired.

I am looking for a way to fire it only if 
$form_state-&gt;getValue('family_state') === 1

this is the module_name.module code:



// DEFINE TZ RETURN VALUES
define(TZ_ELEGAL_INPUT, -1);
define(TZ_NOT_VALID, -2);
define(TZ_VALID, 1);

function ValidateID($str)
{


    //Convert to string, in case numeric input
    $IDnum = strval($str);

    //validate correct input
    if(! ctype_digit($IDnum)) // is it all digits
        return TZ_ELEGAL_INPUT;
    if((strlen($IDnum)&gt;9) || (strlen($IDnum)&lt;5))
        return TZ_ELEGAL_INPUT;

    //If the input length less then 9 and bigger then 5 add leading 0
    while(strlen($IDnum&lt;9))
    {
    $IDnum = '0'. $IDnum;
}

    $mone = 0;
    //Validate the ID number
    for($i=0; $i&lt;9; $i++)
    {
        $char = mb_substr($IDnum, $i, 1);
        $incNum = intval($char);
        $incNum*=($i%2)+1;
        if($incNum &gt; 9)
            $incNum-=9;
        $mone+= $incNum;
    }

    if($mone%10==0)
        return TZ_VALID;
    else
        return TZ_NOT_VALID;

}


function achva_form_alter(&amp;$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    switch($form_id){
    case 'webform_submission_qyt_qlyth_mwrwt_mmnwt_wqdmyh_kyt_add_form':
        $form['#validate'][] = '_achva_tz_validate';
        break;
    default:
        $form['#validate'][] = '_achva_tz_test_validate';
        break;
    }
}

function _achva_tz_test_validate(&amp;$form, $form_state) {

    if(ValidateID($form_state-&gt;getValue('idno')) !== 1) {
        $form_state-&gt;setErrorByName('title', t('Please enter a valid ids number'));
    }
}


function _achva_tz_validate(&amp;$form, $form_state) {



if(ValidateID($form_state-&gt;getValue('idno')) !== 1) {
    $form_state-&gt;setErrorByName('idtitle', t('Please enter a valid id number'));
}

if(ValidateID($form_state-&gt;getValue('zug_id')) !== 1 &amp;&amp; $form_state-&gt;getValue('family_state') === 1) {
    $form_state-&gt;setErrorByName('zugidtitle', t('Please enter a valid zug id number'));
     }
  }
You anyway have a problem here:

//If the input length less then 9 and bigger then 5 add leading 0
while(strlen($IDnum&lt;9))
{
$IDnum = '0'. $IDnum;


}

it should be:

while(strlen($IDnum)&lt;9)
{
$IDnum = '0'. $IDnum;


}