0

I'd like to be able to trigger the validations for a field, including relevant entity constraints, on a change (or equivalent) event for the field using AJAX. But I cannot figure out how to make that happen. It looks like the validation code is being called, but validations are disabled in form state (limit_validation_errors is set to []). I can hack that but I assume it's doing that for a reason.

I would have thought that this is a pretty common thing to do but either no or I am failing at picking the right search keywords.

3
  • There are some nice suggestions in this thread: stackoverflow.com/questions/7903073/…
    – bmunslow
    Dec 13, 2022 at 15:36
  • This is what I have found so far, they are all talking about performing validations on an AJAX submit. What I want to do is validate a single field when it changes. I think there have been changes since Drupal 7, as well. Dec 13, 2022 at 16:18
  • It's not common, for most on submit is fine. As per Introduction to Form API first paragraph. It's designed so validation only occurs when a form is submitted.
    – No Sssweat
    Dec 13, 2022 at 23:45

1 Answer 1

0

This can be done, it seems, though you have to watch out for the details of the kind of field you are validating.

On the same element of the form where you create your #ajax settings, you can use #limit_validation_errors to validate the fields your ajax callback will replace:

$item['#limit_validation_errors'] = [ ['field_1'], ['field_2'] ];

At first I thought it was ignoring this, but it turns out that the issue was with what I was replacing in the form. For example, each item in a multivalue email field is inside a .js-form-item div, and that's what rendering the element will create. But the "drupal-data-selector" value only applies to the tag inside the div. If I replace the whole field, rather than the element that triggered the ajax callback, the validation errors show up. I'm sure other kinds of elements will have other quirks.

1
  • I am still figuring out the best way to update a single email element - I have to identify that wrapper div and remove the suffix div if there is one - but that's a different problem. Jan 10 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.