AngularJS directive to add a Google reCaptcha to your form

Google reCaptcha is very popular captcha widget from google which you can add in your web form to prevent filling span data in your form or auto generated data. It easily check is real human filling form or some program entering data in form and tying to submit. So in this post I am going to share this popular captcha widget for your angular based app. which you can easily apply on your angular form.

recaptcha-3

Bower

bower install --save angular-recaptcha

npm

npm install --save angular-recaptcha

Usage

IMPORTANT: Keep in mind that the captcha only works when used from a real domain
and with a valid re-captcha key, so this file won't work if you just load it in
your browser.
  • First, you need to get a valid recaptcha key for your domain. Go to http://www.google.com/recaptcha.

  • Include the vc-recaptcha script and make your angular app depend on the vcRecaptcha module.

<script type="text/javascript" src="angular-recaptcha.js"></script>
var app = angular.module('myApp', ['vcRecaptcha']);
  • After that, you can place a container for the captcha widget in your view, and call the vc-recaptcha directive on it like this:
<div
    vc-recaptcha
    key="'---- YOUR PUBLIC KEY GOES HERE ----'"
></div>


Here, the key attribute is passed to the directive’s scope, so you can use either a property in your scope or just a hardcoded string. Be careful to use your public key, not your private one.

Form Validation

By default, if placed in a form using formControl the captcha will need to be checked for the form to be valid.
If the captcha is not checked (if the user has not checked the box or the check has expired) the form will be marked as invalid. The validation key is recaptcha.
You can opt out of this feature by setting the required attribute to false or a scoped variable
that will evaluate to false. Any other value, or omitting the attribute will opt in to this feature.

You can also trigger the validation programatically if the captcha is not required, for example:

vcRecaptchaService.execute(widgetId);

If no widget ID is provided, the first created widget will be executed.

Response Validation

To validate this object from your server, you need to use the API described in the verify section. Validation is outside of the scope of this tool, since is mandatory to do that at the server side.

You can simple supply a value for ng-model which will be dynamically populated and cleared as the response becomes available and expires, respectively. When you want the value of the response, you can grab it from the scoped variable that was passed to ng-model. It works just like adding ng-model to any other input in your form.

...
  <form name="myForm" ng-submit="mySubmit(myFields)">
  ...
  <div
      vc-recaptcha
      ng-model="myFields.myRecaptchaResponse"
  ></div>
  ...
  </form>
...
  ...
  $scope.mySubmit = function(myFields){
    console.log(myFields.myRecaptchaResponse);
  }
  ...

Or you can programmatically get the response that you need to send to your server, use the method getResponse() from the vcRecaptchaService angular service. This method receives an optional argument widgetId, useful for getting the response of a specific reCaptcha widget (in case you render more than one widget). If no widget ID is provided, the response for the first created widget will be returned.

var response = vcRecaptchaService.getResponse(widgetId); 

Using ng-model is recommended for normal use as the value is tied directly to the reCaptcha instance through the directive and there is no need to manage or pass a widgetId.



Here is the demo script

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>VividCortex reCaptcha Directive Example</title>
 
        <!-- Bootstrap is NOT required, its just here to make the demo look better -->
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
 
        <!-- Include AngularJS -->
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.js"></script>
        <!-- Include the ngReCaptcha directive -->
        <script src="./angular-recaptcha.js"></script>
 
        <!-- define your app and make it depend on vcRecaptcha module -->
        <script>
            var app = angular.module('testApp', ['vcRecaptcha']);
            app.controller('testCtrl', function ($scope, vcRecaptchaService) {
                console.log("this is your app's controller");
                $scope.response = null;
                $scope.widgetId = null;
                $scope.model = {
                    key: '=== REPLACE THIS WITH YOUR PUBLIC ReCaptcha KEY ==='
                };
                $scope.setResponse = function (response) {
                    console.info('Response available');
                    $scope.response = response;
                };
                $scope.setWidgetId = function (widgetId) {
                    console.info('Created widget ID: %s', widgetId);
                    $scope.widgetId = widgetId;
                };
                $scope.cbExpiration = function() {
                    console.info('Captcha expired. Resetting response object');
                    vcRecaptchaService.reload($scope.widgetId);
                    $scope.response = null;
                 };
                $scope.submit = function () {
                    var valid;
                    
                    console.log('sending the captcha response to the server', $scope.response);
                    if (valid) {
                        console.log('Success');
                    } else {
                        console.log('Failed validation');
                        
                        
                        vcRecaptchaService.reload($scope.widgetId);
                    }
                };
            });
        </script>
 
    </head>
    <body>
    <div class="container" ng-app="testApp" ng-controller="testCtrl">
 
        <h1>VividCortex reCaptcha Directive Example</h1>
 
            This the <b>recommended</b> way of using the reCaptcha directive.
            Instead of using ng-model to get the challenge and response, you use a service.
            This way it's safer because we don't depend on a timeout hack that we are currently using in the directive.
 
 
        <!-- Call a method in the scope of your controller to handle data submit -->
        <form ng-submit="submit()">
            <div
                vc-recaptcha
                theme="'light'"
                key="model.key"
                on-create="setWidgetId(widgetId)"
                on-success="setResponse(response)"
                on-expire="cbExpiration()"
            ></div>
            <button class="btn" type="submit">Submit</button>
        </form>
 
    </div>
    </body>
</html>

Other Parameters

You can optionally pass a theme the captcha should use, as an HTML attribute:

    <div
        vc-recaptcha
        ng-model="gRecaptchaResponse"
        theme="---- light or dark ----"
        size="---- compact, normal or invisible ----"
        type="'---- audio or image ----'"
        key="'---- YOUR PUBLIC KEY GOES HERE ----'"
        lang="---- language code ----"
    ></div>

Language Codes: https://developers.google.com/recaptcha/docs/language

In this case we are specifying that the captcha should use the theme named light.

Listeners

There are three listeners you can use with the directive, on-create, on-success, and on-expire.

  • on-create: It’s called right after the widget is created. It receives a widget ID, which could be helpful if you have more than one reCaptcha in your site.
  • on-success: It’s called once the user resolves the captcha. It receives the response string you would need for verifying the response.
  • on-expire: It’s called when the captcha response expires and the user needs to solve a new captcha.
<div
    vc-recaptcha
    key="'---- YOUR PUBLIC KEY GOES HERE ----'"
    ng-model="gRecaptchaResponse"
    on-create="setWidgetId(widgetId)"
    on-success="setResponse(response)"
    on-expire="cbExpiration()"
    lang=""
></div>

Example

app.controller('myController', ['$scope', 'vcRecaptchaService', function ($scope, recaptcha) {
    $scope.setWidgetId = function (widgetId) {



    };

    $scope.setResponse = function (response) {

    };

    $scope.cbExpiration = function() {

    };
}]);

Secure Token

If you want to use a secure token pass it along with the site key as an HTML attribute.

<div
    vc-recaptcha
    key="'---- YOUR PUBLIC KEY GOES HERE ----'"
    stoken="'--- YOUR GENERATED SECURE TOKEN ---'"
></div>

Please note that you have to encrypt your token yourself with your private key upfront!
To learn more about secure tokens and how to generate & encrypt them please refer to the reCAPTCHA Docs.

Service Provider

You can use the vcRecaptchaServiceProvider to configure the recaptcha service once in your application’s config function.
This is a convenient way to set your reCaptcha site key, theme, stoken, size, and type in one place instead of each vc-recaptcha directive element instance.
The defaults defined in the service provider will be overrode by any values passed to the vc-recaptcha directive element for that instance.

myApp.config(function(vcRecaptchaServiceProvider){
  vcRecaptchaServiceProvider.setSiteKey('---- YOUR PUBLIC KEY GOES HERE ----')
  vcRecaptchaServiceProvider.setTheme('---- light or dark ----')
  vcRecaptchaServiceProvider.setStoken('--- YOUR GENERATED SECURE TOKEN ---')
  vcRecaptchaServiceProvider.setSize('---- compact, normal or invisible ----')
  vcRecaptchaServiceProvider.setType('---- audio or image ----')
  vcRecaptchaServiceProvider.setLang('---- language code ----')
});

Language Codes: https://developers.google.com/recaptcha/docs/language

You can also set all of the values at once.

myApp.config(function(vcRecaptchaServiceProvider){
  vcRecaptchaServiceProvider.setDefaults({
    key: '---- YOUR PUBLIC KEY GOES HERE ----',
    theme: '---- light or dark ----',
    stoken: '--- YOUR GENERATED SECURE TOKEN ---',
    size: '---- compact, normal or invisible ----',
    type: '---- audio or image ----',
    lang: '---- language code ----'
  });
});

See live demo and download source code.

DEMO | DOWNLOAD

This awesome script developed by VividCortex, Visit their official github repository for more information and follow for future updates.


Don’t forget to Subscribe My Public Notebook for more useful free scripts, tutorials and articles.