function TextFieldTest::testTextFieldValidation
Same name in other branches
- 8.9.x core/modules/text/tests/src/Functional/TextFieldTest.php \Drupal\Tests\text\Functional\TextFieldTest::testTextFieldValidation()
- 10 core/modules/text/tests/src/Functional/TextFieldTest.php \Drupal\Tests\text\Functional\TextFieldTest::testTextFieldValidation()
- 11.x core/modules/text/tests/src/Functional/TextFieldTest.php \Drupal\Tests\text\Functional\TextFieldTest::testTextFieldValidation()
Tests text field validation.
File
-
core/
modules/ text/ tests/ src/ Functional/ TextFieldTest.php, line 50
Class
- TextFieldTest
- Tests the creation of text fields.
Namespace
Drupal\Tests\text\FunctionalCode
public function testTextFieldValidation() {
// Create a field with settings to validate.
$max_length = 3;
$field_name = mb_strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'text',
'settings' => [
'max_length' => $max_length,
],
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'entity_test',
])->save();
// Test validation with valid and invalid values.
$entity = EntityTest::create();
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->assertCount(0, $violations, "Length {$i} does not cause validation error when max_length is {$max_length}");
}
else {
$this->assertCount(1, $violations, "Length {$i} causes validation error when max_length is {$max_length}");
}
}
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.