You are here

public static function Fraction::validateFraction in Fraction 8

Same name and namespace in other branches
  1. 2.x src/Element/Fraction.php \Drupal\fraction\Element\Fraction::validateFraction()

Form element validation handler for #type 'fraction'.

Note that #required is validated by _form_validate() already.

File

src/Element/Fraction.php, line 102

Class

Fraction
Provides a fraction form element.

Namespace

Drupal\fraction\Element

Code

public static function validateFraction(&$element, FormStateInterface $form_state, &$complete_form) {
  $numerator = $element['numerator']['#value'];
  $denominator = $element['denominator']['#value'];

  // If the denominator is empty, but the numerator isn't, print an error.
  if (empty($denominator) && !empty($numerator)) {
    $form_state
      ->setError($element, t('The denominator of a fraction cannot be zero or empty (if a numerator is provided).'));
  }

  // Numerators must be between -9223372036854775808 and 9223372036854775807.
  // Explicitly perform a string comparison to ensure precision.
  if (!empty($numerator) && ((string) $numerator < '-9223372036854775808' || (string) $numerator > '9223372036854775807')) {
    $form_state
      ->setError($element, t('The numerator of a fraction must be between -9223372036854775808 and 9223372036854775807.'));
  }

  // Denominators must be between 1 and 2147483647.
  // Explicitly perform a string comparison to ensure precision.
  if (!empty($denominator) && ((string) $denominator <= '0' || (string) $denominator > '2147483647')) {
    $form_state
      ->setError($element, t('The denominator of a fraction must be greater than 0 and less than 2147483647.'));
  }
}