Score:0

Node form field validations on change with AJAX

ke flag

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.

in flag
There are some nice suggestions in this thread: https://stackoverflow.com/questions/7903073/ajax-form-validate-and-submit/22226414
ke flag
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.
No Sssweat avatar
ua flag
It's not common, for most on submit is fine. As per [Introduction to Form API](https://www.drupal.org/docs/drupal-apis/form-api/introduction-to-form-api) first paragraph. It's designed so validation only occurs when a form is submitted.
Score:0
ke flag

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.

ke flag
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.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.