Call a javascript function on form submission in Umbraco

67 Views Asked by At

Hello Stackoverflow community,

Can someone please share their insights on how can we call a javascript function during form submission in Umbraco frontend and then continue the rest of the workflow ?

Since, I am implementing an invisible recaptcha we have to trigger grecaptcha.execute(); to generate a client token.

I have to execute this script on form submission so that the recaptcha token gets generated.

<script type="text/javascript">
    function  onSubmit(event){
      event.preventDefault();
      grecaptcha.execute();
     }
</script>

And then in the ValidateField method using

 var reCaptchaResponse = context.Request.Form["g-recaptcha-response"].ToString();

I can get the client token for validation.

Any leads are appreciated !

So far I have tried checking documentation of SurafceController however, what I want to execute is in frontend not backend.

Edit :

I have added an event listener on form submission. However, when the form is submitted it doesn't wait for the token generation and then in ValidateSettings -> context.Request.Form["g-recaptcha-response"] is null.

Here is my custom field type code.

@using Umbraco.Forms.Web
@using Microsoft.Extensions.Configuration
@model Umbraco.Forms.Web.Models.FieldViewModel
@inject IConfiguration Configuration
@{
    var siteKey = Configuration.GetSection("ReCaptchaEnterprise")["SiteKey"];
    if (!string.IsNullOrEmpty(siteKey))
    {
        Html.AddFormThemeScriptFile("https://www.google.com/recaptcha/enterprise.js?render=" + siteKey);
        Html.AddFormThemeScriptFile("https://www.google.com/recaptcha/api.js?render="+ siteKey);
        Html.AddFormThemeScriptFile("https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js");
        <div class="g-recaptcha"
             data-sitekey="@siteKey"
             data-size="invisible">
        </div>
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function(){
                var formContainer = document.querySelector(".umbraco-forms-form");
                var form = formContainer.querySelector("form");
                form.addEventListener('submit', (event) => {
                    console.log(grecaptcha.execute());
                }) 
            })       
        </script>
    }
    else
    {
        <p class="error">ERROR: reCAPTCHA is missing the Site Key. Please update the configuration to include a value.</p>
    }
}

Custom class for the custom field type in Umbraco :

using System;
using System.Collections.Generic;
using System.Linq;
using AngleSharp.Io;
using Microsoft.AspNetCore.Http;
using Umbraco.Forms.Core.Enums;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Services;
using Request = Org.BouncyCastle.Asn1.Ocsp.Request;

namespace Crna.ContentManagement.Web.FormsExtensions
{
    public class ReCaptchaEnterprise : Umbraco.Forms.Core.FieldType
    {
        public ReCaptchaEnterprise()
        {
            Id = new Guid(<guid>);
            Name = "ReCaptchaEnterprise";
            Description = "Render a custom reCaptcha enterprise field.";
            Icon = "icon-autofill";
            SortOrder = 10;
            FieldTypeViewName = "FieldType.ReCaptchaEnterprise.cshtml";
        }
        
        // Custom validation in here which will occur when the form is submitted.
        // Any strings returned will cause the submission to be considered invalid.
        // Returning an empty collection of strings will indicate that it's valid to proceed.
        public override IEnumerable<string> ValidateField(Form form, Field field, IEnumerable<object> postedValues, HttpContext context, IPlaceholderParsingService placeholderParsingService, IFieldTypeStorage fieldTypeStorage)
        {
            var returnStrings = new List<string>();

            var reCaptchaResponse = context.Request;
            
            Console.WriteLine("+++++++++++++++++++++ReCaptcha response+++++++++++++++++++++++++++" + context.Request.Form["g-recaptcha-response"]);
            
            // Also validate it against the default method (to handle mandatory fields and regular expressions)
            return base.ValidateField(form, field, postedValues, context, placeholderParsingService, fieldTypeStorage, returnStrings);
        }
    }    
}



1

There are 1 best solutions below

3
Chalas On

You can use the onsubmit event to execute Javascript Code e.g.

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

OR

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

Reference: Form Submit Execute JavaScript Best Practice?