Drupal 8: Webform - how to programmatically prevent or call a form submission? I build a form with the webform module and hooked it to be able to submit it via AJAX:

function mytheme_form_alter(&amp;$form, FormStateInterface $form_state, $form_id)
{
  if ( isset($form['#webform_id']) &amp;&amp; $form['#webform_id'] == 'myform' )
  {
    // add an AJAX callback to the form submission
    $form['actions']['submit']['#ajax'] = array(
      'callback' =&gt; '\Drupal\mymodule\Controller\DefaultController::submitMyForm',
      'event' =&gt; 'click',
    );
  }
}


Now i'd like to prevent the form submission in the submitMyForm-function when a certain condition takes place. How can I achieve that?

And how can I submit it when the condition doesn't take place?



EDIT

This worked:

function submitMyForm(&amp;$form, FormStateInterface $form_state, $form_id)
{
   if ( $condition ) {
      $form_state-&gt;setErrorByName('field_name', t('error message'));
   }
}
Sitepoint has a nice example of Ajax form validation in Drupal 8:

https://www.sitepoint.com/using-ajax-forms-drupal-8/