diff --git a/README.md b/README.md index 965e78d..00cc019 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,13 @@ var app = angular.module('myApp', ['vcRecaptcha']); 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](https://docs.angularjs.org/api/ng/directive/form) using [formControl](https://docs.angularjs.org/api/ng/type/form.FormController) 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. + Response Validation ------------------- diff --git a/src/directive.js b/src/directive.js index 386b5ea..4de5297 100644 --- a/src/directive.js +++ b/src/directive.js @@ -21,6 +21,7 @@ size: '=?', type: '=?', tabindex: '=?', + required: '=?', onCreate: '&', onSuccess: '&', onExpire: '&' @@ -32,6 +33,10 @@ scope.widgetId = null; + if(ctrl && angular.isDefined(attrs.required)){ + scope.$watch('required', validate); + } + var removeCreationListener = scope.$watch('key', function (key) { if (!key) { return; @@ -44,10 +49,9 @@ var callback = function (gRecaptchaResponse) { // Safe $apply $timeout(function () { - if(ctrl){ - ctrl.$setValidity('recaptcha',true); - } scope.response = gRecaptchaResponse; + validate(); + // Notify about the response availability scope.onSuccess({response: gRecaptchaResponse, widgetId: scope.widgetId}); }); @@ -64,9 +68,7 @@ }).then(function (widgetId) { // The widget has been created - if(ctrl){ - ctrl.$setValidity('recaptcha',false); - } + validate(); scope.widgetId = widgetId; scope.onCreate({widgetId: widgetId}); @@ -88,14 +90,19 @@ } function expired(){ - if(ctrl){ - ctrl.$setValidity('recaptcha',false); - } scope.response = ""; + validate(); + // Notify about the response availability scope.onExpire({widgetId: scope.widgetId}); } + function validate(){ + if(ctrl){ + ctrl.$setValidity('recaptcha', scope.required === false ? null : Boolean(scope.response)); + } + } + function cleanup(){ // removes elements reCaptcha added. angular.element($document[0].querySelectorAll('.pls-container')).parent().remove();