How to validate a field value programatically in Drupal 8? I've created a module for Drupal8 that checks against values in the user register and set an error if the values do no match with something you have entered in a custom form.

My module has got a form where you add a list of username you don't want the user to take and a custom message to display as an error.

Forms works perfectly, I can store data, edit it etc... It is stored under src/Form/ and settings are under config/install

Now when I'm trying to hook the user register form validate I got an error regarding form_set_error():


  PHP Fatal error:  Call to undefined function form_set_error() 


Also I think I'm not using $form_state in the right way (but it does the job)

Here's the code in my_module.module:

function my_module_form_user_register_form_alter(&amp;$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 $form['#validate'][] = 'my_module_user_validate';
}

/**
 * Custom validation function.
 */
function my_module_user_validate(&amp;$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    // get module settings
    $config = \Drupal::config('my_module.settings');

    // Convert $form_state to an array as it has been passed as object, it looks wrong but I could not find any documentation at the moment
    $form_state = get_object_vars($form_state);
    $name = $form_state['values']['name']);
    $usernames = $config-&gt;get('my_modules_usernames');
    // Username are inserted in a text area separated by an enter key
    $usernames = $usernames != '' ? explode("\r\n", $usernames) : array();
    foreach ($usernames as $username) {
      if ($username == $name[1]) {
        //apparently in Drupal 8 form_set_error does not work anymmore
        form_set_error('mail', $config-&gt;get('my_module_message'));
      }
    }
  }
The $form_state now become a classed object as documented here

You can use getValue() to get field value instead of converting it into an array

$form_state-&gt;getValue('name');


instead of:

$form_state = get_object_vars($form_state);
$name = $form_state['values']['name']);


Same thing for form_set_value.

And form_set_error() became $form_state-&gt;setErrorByName().