public static function Signature::validateElement in SignatureField 1.x
Validate a signature element.
Parameters
array $element: The element being validated.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
array $complete_form: The complete form structure.
File
- src/
Element/ Signature.php, line 49
Class
- Signature
- Provides a form element for a signature.
Namespace
Drupal\signaturefield\ElementCode
public static function validateElement(array &$element, FormStateInterface $form_state, array &$complete_form) {
if ($element['#value'] === '') {
return;
}
if (strpos($element['#value'], 'data:image/png;base64,') !== 0) {
$form_state
->setError($element, t('No valid signature has been submitted.'));
return;
}
// Create a temporary file for validation.
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$directory = $file_system
->realpath('temporary://');
if (!($file = tempnam($directory, 'signature'))) {
$form_state
->setError($element, t('The signature image could not be validated.'));
return;
}
try {
// Save the image.
file_put_contents($file, base64_decode(mb_substr($element['#value'], 21)));
// Validate it.
/** @var \Drupal\Core\Image\ImageFactory $image_factory */
$image_factory = \Drupal::service('image.factory');
$image = $image_factory
->get($file);
if (!$image
->isValid() || $image
->getMimeType() !== 'image/png') {
$form_state
->setError($element, t('No valid signature has been submitted.'));
}
} finally {
unlink($file);
}
}