TextFieldTestCase::testTextFieldValidation

  1. drupal
    1. 8
    2. 7
Versions
7 TextFieldTestCase::testTextFieldValidation()

Test text field validation.

Code

modules/field/modules/text/text.test, line 34

<?php
function testTextFieldValidation() {
  // Create a field with settings to validate.
  $max_length = 3;
  $this->field = array(
    'field_name' => drupal_strtolower($this->randomName()), 
    'type' => 'text', 
    'settings' => array(
      'max_length' => $max_length,
    ),
  );
  field_create_field($this->field);
  $this->instance = array(
    'field_name' => $this->field['field_name'], 
    'entity_type' => 'test_entity', 
    'bundle' => 'test_bundle', 
    'widget' => array(
      'type' => 'text_textfield',
    ), 
    'display' => array(
      'default' => array(
        'type' => 'text_default',
      ),
    ),
  );
  field_create_instance($this->instance);
  // Test valid and invalid values with field_attach_validate().
  $entity = field_test_create_stub_entity();
  $langcode = LANGUAGE_NONE;
  for ($i = 0; $i <= $max_length + 2; $i++) {
    $entity->{$this->field['field_name']}[$langcode][0]['value'] = str_repeat('x', $i);
    try {
      field_attach_validate('test_entity', $entity);
      $this->assertTrue($i <= $max_length, "Length $i does not cause validation error when max_length is $max_length");
    }
    catch (FieldValidationException $e) {
      $this->assertTrue($i > $max_length, "Length $i causes validation error when max_length is $max_length");
    }
  }
}
?>