You are here

function TextFieldTest::testTextFieldValidation in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/text/src/Tests/TextFieldTest.php \Drupal\text\Tests\TextFieldTest::testTextFieldValidation()

Test text field validation.

File

core/modules/text/src/Tests/TextFieldTest.php, line 38
Contains \Drupal\text\Tests\TextFieldTest.

Class

TextFieldTest
Tests the creation of text fields.

Namespace

Drupal\text\Tests

Code

function testTextFieldValidation() {

  // Create a field with settings to validate.
  $max_length = 3;
  $field_name = Unicode::strtolower($this
    ->randomMachineName());
  $field_storage = entity_create('field_storage_config', array(
    'field_name' => $field_name,
    'entity_type' => 'entity_test',
    'type' => 'text',
    'settings' => array(
      'max_length' => $max_length,
    ),
  ));
  $field_storage
    ->save();
  entity_create('field_config', array(
    'field_storage' => $field_storage,
    'bundle' => 'entity_test',
  ))
    ->save();

  // Test validation with valid and invalid values.
  $entity = entity_create('entity_test');
  for ($i = 0; $i <= $max_length + 2; $i++) {
    $entity->{$field_name}->value = str_repeat('x', $i);
    $violations = $entity->{$field_name}
      ->validate();
    if ($i <= $max_length) {
      $this
        ->assertEqual(count($violations), 0, "Length {$i} does not cause validation error when max_length is {$max_length}");
    }
    else {
      $this
        ->assertEqual(count($violations), 1, "Length {$i} causes validation error when max_length is {$max_length}");
    }
  }
}