I have a registration form :
<div class="register-error" id="register-error">{{ form.status_messages_user_register_form }}</div> <div class="row"> <div class="col-sm-6">{{ form.field_first_name }}</div> <div class="col-sm-6">{{ form.field_last_name }}</div></div> <div class="clear"></div> {{ form.account.mail }} {{ form.account.name }} <div class="row"> <div class="col-sm-6">{{ form.account.pass.pass1 }}</div> <div class="col-sm-6">{{ form.account.pass.pass2 }}</div></div> <div class="clear"></div> {{ form.form_build_id }} {# required #} {{ form.form_token }}{# required #} {{ form.form_id }} {# required #} {{ form.actions }}
Now i want to add custom validation for the registration.I have a custom ajax handler for registration using form alter:
$form['actions']['submit']['#ajax'] = [ 'callback' => 'custom_register_form_ajax_validate', 'event' => 'click', '#attributes' => [ 'class' => [ 'use-ajax', ], ], ]; $form['#attached']['library'][] = 'core/drupal.dialog.ajax'; $form['#attached']['library'][] = 'core/drupal.ajax'; $form['#prefix'] = '<div id="email-valid"></div>';
And this is my function :
function custom_register_form_ajax_validate(&$form, $form_state){ $response = new AjaxResponse(); $form_state->setTemporaryValue('entity_validated', TRUE); $firstname = $form['field_first_name']['widget']['#default_value']; $email = $form_state->getValue('mail'); $pass1 = $form_state->getValue('pass1'); $pass2 = $form_state->getValue('pass2'); if($firstname == ''){ $text = '<h5 style="color:red;">Firstname is required.</h5>'; $response->addCommand(new InvokeCommand('.form-text', 'css', array('border-bottom', '2px solid red'))); $response->addCommand(new HtmlCommand('#email-valid', $text)); } if($lastname == ''){ $text = '<h5 style="color:red;">Lastname is required.</h5>'; $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red'))); $response->addCommand(new HtmlCommand('#email-valid', $text)); } if($email == ''){ $text = '<h5 style="color:red;">Email field is required.</h5>'; $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red'))); $response->addCommand(new HtmlCommand('#email-valid', $text)); } }
I want to validate “Firstname is required” condition.But when i submit and validate the form,always showing “Email field is required”.
How can i solve this issue?