How to validate a single field via AJAX?

bernhard
Member | 51
+
0
-

Hi,

how would I validate inputs that need a DB lookup or an AJAX request? There are many use cases for that, eg checking whether the entered email already exists, checking an entered UID via REST, checking an entered coupon, etc.

I only found this thread: https://forum.nette.org/…abase-lookup

@jiripudil mentioned that “it would take some extra effort in this particular use case because it would require an AJAX request to the server.”

Is there any best practise how to do this? How would I show errors from JS if the AJAX request returns “failed” or something?

Thank you in advance!

Rick Strafy
Nette Blogger | 81
+
0
-

Hi, I would handle it in onSuccess form callback where I would add flashMessage to presenter (and then redraw snippet with flash messages, I have it automatic if ajax request is detected and request have “_fid” parameter, I always redraw flashes in startup/beforeRender), because it seems to me like form data are valid as they are, and it's maybe better to handle exceptions like UserAlreadyExists in onSuccess where you can have multiple try-catches under each other.

Optionally, you can maybe add error to that element in onSuccess, like $form[‘email’]->addError.. and redraw form, but I haven't tried that I think, there may be some problem that password will reset itself from form or something.