You are here

public function ValidationTest::testCustomRequiredError in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/system/tests/src/Functional/Form/ValidationTest.php \Drupal\Tests\system\Functional\Form\ValidationTest::testCustomRequiredError()

Tests #required with custom validation errors.

See also

\Drupal\form_test\Form\FormTestValidateRequiredForm

File

core/modules/system/tests/src/Functional/Form/ValidationTest.php, line 220

Class

ValidationTest
Tests form processing and alteration via form validation handlers.

Namespace

Drupal\Tests\system\Functional\Form

Code

public function testCustomRequiredError() {
  $form = \Drupal::formBuilder()
    ->getForm('\\Drupal\\form_test\\Form\\FormTestValidateRequiredForm');

  // Verify that a custom #required error can be set.
  $edit = [];
  $this
    ->drupalGet('form-test/validate-required');
  $this
    ->submitForm($edit, 'Submit');
  foreach (Element::children($form) as $key) {
    if (isset($form[$key]['#required_error'])) {
      $this
        ->assertSession()
        ->pageTextNotContains($form[$key]['#title'] . ' field is required.');
      $this
        ->assertSession()
        ->pageTextContains((string) $form[$key]['#required_error']);
    }
    elseif (isset($form[$key]['#form_test_required_error'])) {
      $this
        ->assertSession()
        ->pageTextNotContains($form[$key]['#title'] . ' field is required.');
      $this
        ->assertSession()
        ->pageTextContains((string) $form[$key]['#form_test_required_error']);
    }
  }
  $this
    ->assertSession()
    ->pageTextNotContains('An illegal choice has been detected. Please contact the site administrator.');

  // Verify that no custom validation error appears with valid values.
  $edit = [
    'textfield' => $this
      ->randomString(),
    'checkboxes[foo]' => TRUE,
    'select' => 'foo',
  ];
  $this
    ->drupalGet('form-test/validate-required');
  $this
    ->submitForm($edit, 'Submit');
  foreach (Element::children($form) as $key) {
    if (isset($form[$key]['#required_error'])) {
      $this
        ->assertSession()
        ->pageTextNotContains($form[$key]['#title'] . ' field is required.');
      $this
        ->assertSession()
        ->pageTextNotContains((string) $form[$key]['#required_error']);
    }
    elseif (isset($form[$key]['#form_test_required_error'])) {
      $this
        ->assertSession()
        ->pageTextNotContains($form[$key]['#title'] . ' field is required.');
      $this
        ->assertSession()
        ->pageTextNotContains((string) $form[$key]['#form_test_required_error']);
    }
  }
  $this
    ->assertSession()
    ->pageTextNotContains('An illegal choice has been detected. Please contact the site administrator.');
}