Form AJAX validation

Hi,

I use form validation below:

 $data = Request::validate([
                'email' => 'required|email',
                'gdpr-radio-button' => 'required',
            ]);

If one of them is empty I render an alert message.

If validaiton successfully run forward the code, and depends on Http request response, I return a Response to frontend:

 try {
                $result = $apiInstance->createContact($createContact);
                return Response::make('Successfully subscribed backend', 200);
            } catch (Exception $e) {
                return Response::make([
                    'error' => json_decode($e->getResponseBody())->code,
                    'message' => json_decode($e->getResponseBody())->message
                ], 400); 
            }

On the frontend I use the following code for submit and handling:

 oc.request('#newsletterForm', 'onSubscribe',
                                    {
                                        success: function (data) {
                                            this.success(data).done(function () {
                                                console.log("successfully subscribed");
                                            });
                                        },
                                        error: function (data) {
                                            console.log('contact already existttt', data.error);
                                            if (data.error == 'duplicate_parameter') {
                                                console.log('render a message that you are already subscribed');
                                            }
                                        }
                                    }
                                )

But if I use ‘‘error: function (data) {…’’, the email and gdpr-radio-button alert messages does not rendering.

Could you help me please, how to manage properly validation errors, and responses?

Thank you,
Zs

You’re missing this.error(data).done(...) in your error handling function. It’s the same principal as for the success handler: you’ll have to invoke the default handler so ocms can render the messages, set the classes etc.

  • Update:
    Sorry, that’s probably not something that exists ;-). But you can try, maybe thats an undocumented feature. But as the docs state, you’ll have to manage the error state by yourself:
1 Like