How can I conditionally create a user account based on field in registration? Here is the scenario:
Prospective employees (PE) who need to access this Drupal site for onboarding resources will be sent an access code from someone in HR (to prevent random people from creating accounts).
The PE goes to Drupal site and &quot;registers&quot; for a user account and they enter the access code into a field.
Only approve the account if the access code is correct. If it is correct, approve account and set role to prospect. If it is not correct, block account (until that user registers with correct access code or alternately, someone in HR manually approves it).
What should the account settings be for who can register account? How to test access value and approve/grant role or block based on registration field? Is there a hook or class to extend?
Create a new field on the user object, field_registration_code.

Set the form field to show on the registration page.

Use hook_form_alter() to hide the field when not registering, if the code is not to be used in the future. Don't hide the form field on the 'manage form' tab, else it will not be rendered on the registration page.

Create a service with the following method:
/**
 * Validates a registration code.
 *
 * This function checks if the submitted  code is a valid
 * registration code, and if it is, invalidates the code, and
 * returns TRUE. If the access code is invalid, it returns FALSE.
 *
 * @param string $registrationCode
 *   The code to be validate.
 *
 * @return bool
 *   TRUE if the code was valid, FALSE otherwise.
 */
 public function validateRegistrationCode(string $registrationCode): bool;


Implement hook_ENTITY_TYPE_insert(), implemented as hook_user_insert(). This is called after the user entity has been saved. You can use that hook to check if the given code is validated, and if not, block the account. It can then be activated by an admin through the admin interface.
function HOOK_user_insert(EntityInterface $user) {
  if ($this-&gt;myService-&gt;validateRegistrationCode($entity-&gt;field_registration_code-&gt;value)) {
    // Add roles to user here.
  }
  else {
    $user-&gt;block()-&gt;save();
  }
}