You are here

public function ValidationTest::testPatternValidation in Drupal 8

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

Tests #pattern validation.

File

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

Class

ValidationTest
Tests form processing and alteration via form validation handlers.

Namespace

Drupal\Tests\system\Functional\Form

Code

public function testPatternValidation() {
  $textfield_error = t('%name field is not in the right format.', [
    '%name' => 'One digit followed by lowercase letters',
  ]);
  $tel_error = t('%name field is not in the right format.', [
    '%name' => 'Everything except numbers',
  ]);
  $password_error = t('%name field is not in the right format.', [
    '%name' => 'Password',
  ]);

  // Invalid textfield, valid tel.
  $edit = [
    'textfield' => 'invalid',
    'tel' => 'valid',
  ];
  $this
    ->drupalPostForm('form-test/pattern', $edit, 'Submit');
  $this
    ->assertRaw($textfield_error);
  $this
    ->assertNoRaw($tel_error);
  $this
    ->assertNoRaw($password_error);

  // Valid textfield, invalid tel, valid password.
  $edit = [
    'textfield' => '7seven',
    'tel' => '818937',
    'password' => '0100110',
  ];
  $this
    ->drupalPostForm('form-test/pattern', $edit, 'Submit');
  $this
    ->assertNoRaw($textfield_error);
  $this
    ->assertRaw($tel_error);
  $this
    ->assertNoRaw($password_error);

  // Non required fields are not validated if empty.
  $edit = [
    'textfield' => '',
    'tel' => '',
  ];
  $this
    ->drupalPostForm('form-test/pattern', $edit, 'Submit');
  $this
    ->assertNoRaw($textfield_error);
  $this
    ->assertNoRaw($tel_error);
  $this
    ->assertNoRaw($password_error);

  // Invalid password.
  $edit = [
    'password' => $this
      ->randomMachineName(),
  ];
  $this
    ->drupalPostForm('form-test/pattern', $edit, 'Submit');
  $this
    ->assertNoRaw($textfield_error);
  $this
    ->assertNoRaw($tel_error);
  $this
    ->assertRaw($password_error);

  // The pattern attribute overrides #pattern and is not validated on the
  // server side.
  $edit = [
    'textfield' => '',
    'tel' => '',
    'url' => 'http://www.example.com/',
  ];
  $this
    ->drupalPostForm('form-test/pattern', $edit, 'Submit');
  $this
    ->assertNoRaw(t('%name field is not in the right format.', [
    '%name' => 'Client side validation',
  ]));
}