You are here

public function LengthFieldValidationRule::validate in Field Validation 8

Overrides FieldValidationRuleBase::validate

File

src/Plugin/FieldValidationRule/LengthFieldValidationRule.php, line 91

Class

LengthFieldValidationRule
LengthFieldValidationRule.

Namespace

Drupal\field_validation\Plugin\FieldValidationRule

Code

public function validate($params) {
  $value = isset($params['value']) ? $params['value'] : '';
  $rule = isset($params['rule']) ? $params['rule'] : null;
  $context = isset($params['context']) ? $params['context'] : null;
  $settings = array();
  if (!empty($rule) && !empty($rule->configuration)) {
    $settings = $rule->configuration;
  }

  //$settings = $this->rule->settings;
  if ($value != '') {
    $flag = TRUE;
    if (!empty($settings['strip_tags'])) {
      $value = strip_tags($value);
    }
    if (!empty($settings['trim'])) {
      $value = trim($value);
    }
    $length = mb_strlen($value, 'UTF-8');
    if (isset($settings['min']) && $settings['min'] != '') {

      //$min = token_replace($settings['min'], array($this->get_token_type() => $this->entity));
      $min = $settings['min'];
      if ($length < $min) {
        $flag = FALSE;
      }
    }
    if (isset($settings['max']) && $settings['max'] != '') {

      //$max = token_replace($settings['max'], array($this->get_token_type() => $this->entity));
      $max = $settings['max'];
      if ($length > $max) {
        $flag = FALSE;
      }
    }
    if (!$flag) {

      //$this->set_error($token);
      $context
        ->addViolation($rule
        ->getErrorMessage());
    }
  }

  //return true;
}