Required.php in Clientside Validation 2.0.x
File
src/Plugin/CvValidator/Required.php
View source
<?php
namespace Drupal\clientside_validation\Plugin\CvValidator;
use Drupal\clientside_validation\CvValidatorBase;
use Drupal\Core\Form\FormStateInterface;
class Required extends CvValidatorBase {
protected $states = [
'required' => 'required',
'optional' => 'optional',
'!required' => '!required',
'!optional' => '!optional',
];
protected function getRules($element, FormStateInterface $form_state) {
$is_required = $this
->getAttributeValue($element, 'required');
$states = $this
->getAttributeValue($element, 'states') ?: [];
$is_conditionally_required = FALSE;
if (is_array($states) && !empty($states)) {
$is_conditionally_required = array_intersect_key($this->states, $states);
}
if ($is_required || $is_conditionally_required) {
$message = $element['#required_error'] ?? $this
->t('@title field is required.', [
'@title' => $this
->getElementTitle($element),
]);
return [
'messages' => [
'required' => $message,
],
];
}
}
}