Can't loop through $form_state->setErrorByName? I want to display an error message if the form field is empty.

  public function validateForm(array &amp;$form, FormStateInterface $form_state) {
      $entry = array(
        'name' =&gt; $form_state-&gt;getValue('name'),
        'lastname' =&gt; $form_state-&gt;getValue('lastname'),
        'cardnumber' =&gt; $form_state-&gt;getValue('cardnumber'),
        'month' =&gt; $form_state-&gt;getValue('month'),
        'year' =&gt; $form_state-&gt;getValue('year'),
        'cvv' =&gt; $form_state-&gt;getValue('cvv'),    
    );
    foreach ($entry as $key =&gt; $value) {
     if (empty($value)) { 

      $form_state-&gt;setErrorByName($key, $this-&gt;t('cannot be empty.'));

        } 
     }
  }


but I only get:


  cannot be empty.


If I use instead:

foreach ($entry as $key =&gt; $value) {
  if (empty($value)) { 

    drupal_set_message(t('&lt;b&gt;%key&lt;/b&gt; cannot be empty.', ['%key' =&gt; $key]), 'error');

    } 
}


Results how I want it:


  name cannot be empty. 
  
  lastname cannot be empty. 
  
  cardnumber cannot be empty.
  
  month cannot be empty. 
  
  year cannot be empty. 
  
  cvv cannot be empty.


Except the problem here is that the form input box does not become highlighted in red.

How can I make it loop through the first method? or is it like that by design?
I think you simply need to replace:

$form_state-&gt;setErrorByName($key, $this-&gt;t('cannot be empty.'));


with

$form_state-&gt;setErrorByName($key, $this-&gt;t('&lt;b&gt;%key&lt;/b&gt; cannot be empty.', ['%key' =&gt; $key]));


According to the docs, the first parameter will identify the field and the second will be the message to output. 

In your code, the $message string is outputed as expected, you need to prefix it with the $key parameter, the same way you do with drupal_set_message.