You are here

protected function Required::getRules in Clientside Validation 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/CvValidator/Required.php \Drupal\clientside_validation\Plugin\CvValidator\Required::getRules()
  2. 3.0.x src/Plugin/CvValidator/Required.php \Drupal\clientside_validation\Plugin\CvValidator\Required::getRules()
  3. 2.0.x src/Plugin/CvValidator/Required.php \Drupal\clientside_validation\Plugin\CvValidator\Required::getRules()

Get the validation rules for this form element.

Return value

array An array with following keys:

  • rules: An array with the rulename as key and the rule arguments as value.
  • messages: An array with the rulename as key and the message for this rule as argument.

Overrides CvValidatorBase::getRules

File

src/Plugin/CvValidator/Required.php, line 36

Class

Required
Provides a 'required' validator.

Namespace

Drupal\clientside_validation\Plugin\CvValidator

Code

protected function getRules($element, FormStateInterface $form_state) {
  $is_required = $this
    ->getAttributeValue($element, 'required');
  $states = $this
    ->getAttributeValue($element, 'states') ?: [];
  if (is_array($states)) {
    $is_conditionally_required = array_diff_key($this->states, $states);
  }
  else {
    $is_conditionally_required = $this->states;
  }

  // Drupal already adds the required attribute, so we don't need to set the
  // required rule.
  if ($is_required || $is_conditionally_required) {
    $message = $element['#required_error'] ?? $this
      ->t('@title is required.', [
      '@title' => $this
        ->getElementTitle($element),
    ]);
    return [
      'messages' => [
        'required' => $message,
      ],
    ];
  }
}