Programmatically validate a user I have created a webform which when submitted will create a new user for my Drupal 8 site.

The user must enter his username, email, and some additional data.

I am using below code to create &amp; validate a user:
    

namespace Drupal\my_module\Plugin\WebformHandler;

use Symfony\Component\HttpFoundation\RedirectResponse;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;

use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
// use Drupal\taxonomy\Entity\Term;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create New User Account when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Create New User Account",
 *   label = @Translation("Create New User Account"),
 *   category = @Translation("Entity Create"),
 *   description = @Translation("Create New User Account when a webform submission is submitted."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class CreateNewAccountHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

// Function to be fired while submitting the Webform.
public function submitForm(array &amp;$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

// Build Drupal DateTime &amp; set correct format for your query.
  $current_time = \Drupal::time()-&gt;getCurrentTime();

// Get an array of the values from the submission.
    $values = $webform_submission-&gt;getData();

    // Get 'Username' Value.
    $username = $values['username'];

    // Get 'Password' Value.
    $password = $values['password'];    

    // Get 'Full Name' Value.
    $FullName = $values['full_name']; 

    // Get 'Phone Number' Value.
    $PhoneNumber = $values['phone_number']; 

    // Get 'Email' Value.
    $email = $values['email'];

// Create user object.
    $language = \Drupal::languageManager()-&gt;getCurrentLanguage()-&gt;getId();
    $new_user = \Drupal\user\Entity\User::create();

    //Mandatory fields.
    $new_user-&gt;setPassword($password);
    $new_user-&gt;setEmail($email);
    $new_user-&gt;setUsername($username);    // Alphanumeric (abc, 123), space ( ), period (.), hyphen (-), apostrophe ('), underscore ( _ ), and the @ sign are only allowed.
    $new_user-&gt;set("langcode", $language);
    $new_user-&gt;set("preferred_langcode", $language);
    $new_user-&gt;set("preferred_admin_langcode", $language);
    $new_user-&gt;enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object.

    //Optional Fields
    $new_user-&gt;set("init", 'email');

    // Custom Fields
    $new_user-&gt;set("field_full_name", $FullName);
    $new_user-&gt;set("field_ph_nbr", $PhoneNumber);

    // Validate the user for possible errors.
    $violations = $new_user-&gt;validate();
    if (count($violations) &gt; 0) {
      $property = $violations[0]-&gt;getPropertyPath();
      $msg      = $violations[0]-&gt;getMessage();

    // Show a custom message to user.
        \Drupal::messenger()-&gt;addError(t("$msg"));

      return FALSE;
    }

    // Activate the user Object (Status = Active).
    $new_user-&gt;activate();

    //Save user
    $new_user-&gt;save();

    // Get the new user ID.
    $new_user_id = $new_user-&gt;id();

    // Log in the user.
    user_login_finalize($new_user);


However, every time I try to create a new user using the webform, I got the below error:

This value is not a valid email address.


I have tried with:


someone@hotmail.com
someone@outlook.com
someone@gmail.com


What is wrong with my code ?
The error message doesn't specify which field caused the validation error. In this case, the error is caused by setting the init field with a value that isn't a valid email address.
Differently from Drupal 7, in Drupal 8 the init field for the User entity is created using the email datatype. (See User::baseFieldDefinitions().)
$fields['init'] = BaseFieldDefinition::create('email')
  -&gt;setLabel(t('Initial email'))
  -&gt;setDescription(t('The email address used for initial account creation.'))
  -&gt;setDefaultValue('');

Differently from the mail field, it doesn't get further constrains. (Compare the code used to create the init field with the following code.)
$fields['mail'] = BaseFieldDefinition::create('email')
  -&gt;setLabel(t('Email'))
  -&gt;setDescription(t('The email of this user.'))
  -&gt;setDefaultValue('')
  -&gt;addConstraint('UserMailUnique')
  -&gt;addConstraint('UserMailRequired')
  -&gt;addConstraint('ProtectedUserField');

Still, as any entity field whose datatype is email, it has a constrain defined in the annotation of that datatype.
@DataType(
   id = &quot;email&quot;,
   label = @Translation(&quot;Email&quot;),
   constraints = {&quot;Email&quot; = {}}
)

(The classes defining that constraint are EmailConstraint and EmailValidator.)
Setting the init field for the User entity is optional, but it's generally used from administrators of a site when users claim they created an account for which they cannot retrieve the password they lost.
Depending on the purpose of the code you are using, you can either set the init field, or not. If you set it, it must set to a valid email value.