Form field validator
You can do this with a callback, so that it will work whereever you use it in the form tree:

Add this to your form element:

'#element_validate' =&gt; [[get_class($this), 'validateNumber']],


And put the callback in the form class:

public static function validateNumber(&amp;$element, FormStateInterface $form_state, &amp;$complete_form) {
    $value = $element['#value'];
    if ($value === '') {
      return;
    }

    $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];

    // Ensure the input is numeric.
    if (!is_numeric($value)) {
      $form_state-&gt;setError($element, t('%name must be a number.', array('%name' =&gt; $name)));
      return;
    }
}


(for the callback I've used some of the code from the html5 number element)