reCAPTCHA protects internet users from spam and abuse wherever they go. Here is a ‘CaptchaField’ class which you can set to validate form. It changes the validation of the field, so you can bind appropriate buttons to the form.

To get it work you will have to register your site on the this page. Register your site URL there and get the key. Add the following code to the header of your index.html file.

<header>
...
...
    <sript src="https://www.google.com/recaptcha/api.js?onload=recaptchaOnload&render=explicit" async defer></script>
    <script type="text/javascript">
        function recaptchaOnload() {
            Ext.GlobalEvents.fireEvent('GreCaptchaLoad');
        }
    </script>
...
...
</header>

 

The field also fires the following events:

  • RecaptchaInValid
  • RecaptchaValid
  • RecaptchaExpired
  • RecaptchaErrorCallback

 

Ext.define('CaptchaField', {
    extend: 'Ext.form.field.Base',

    alias: 'widget.captchafield',

    fieldSubTpl: [
        '<div id="{captchaId}" class="{gRecaptcha}" data-sitekey="{dataSiteKey}"></div>'
    ],

    isCaptchaValid: false,

    initComponent: function() {
        Ext.GlobalEvents.on('GreCaptchaLoad', this.renderGCaptcha, this);
        this.callParent()
    },

    getSubTplData: function(fieldData) {
        fieldData.dataSiteKey = this.dataSiteKey;
        fieldData.gRecaptcha = 'g-recaptcha';
        fieldData.captchaId = this.getGCaptchaDivId();
        return fieldData;
    },

    getGCaptchaDivId: function() {
        return this.getId() + '-greCaptchaDiv';
    },

    renderGCaptcha: function() {
        var me = this;
        grecaptcha.render(this.getGCaptchaDivId(), {
          'sitekey' : this.dataSiteKey,
          'callback' : function(response) {me.verifyCallback.call(me, response)},
          'expired-callback': function() {me.onRecaptchaExpired.call(me)},
          'error-callback': function() {me.onErrorCallback.call(me)},
          'theme' : 'dark'
        });
    },

    verifyCallback: function(response) {
        this.isCaptchaValid = (response.length > 0);
        this.fireEvent('validitychange', this, this.isCaptchaValid);
        if(this.isCaptchaValid) {
            this.fireEvent('RecaptchaInValid', this);
        } else {
            this.fireEvent('RecaptchaValid', this);
        }
    },

    onRecaptchaExpired: function() {
        console.log('onRecaptchaExpired');
        this.isCaptchaValid = false;
        this.fireEvent('validitychange', this, this.isCaptchaValid);
        this.fireEvent('RecaptchaExpired', this);
    },

    onErrorCallback: function() {
        this.isCaptchaValid = false;
        this.fireEvent('validitychange', this, this.isCaptchaValid);
        this.fireEvent('RecaptchaErrorCallback', this);
    },

    isValid : function() {
        var me = this;
        return me.disabled || this.isCaptchaValid;
    },
});