Skip to content

Instantly share code, notes, and snippets.

@laurentgoudet
Created August 1, 2014 08:25
Show Gist options
  • Save laurentgoudet/f9a697c28ff56b18b895 to your computer and use it in GitHub Desktop.
Save laurentgoudet/f9a697c28ff56b18b895 to your computer and use it in GitHub Desktop.
MailGun's Guardpost email validation directive for AngularJS - How to create Async directives with $validators in Angular >= v1.3.0-beta.16
'use strict';
/* jshint camelcase: false */
angular.module('lgValidation')
// Uses the Guardpost API from MailGun to validation the
// email addresses and provide suggestions
.directive('lgGuardpost', function($http, $document,
MAILGUN_BASE_URL, MAILGUN_API_KEY) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
var isValid = false; // invalid value (e.g. incorrect email)
var validatedValue; // the value that has been validated
ctrl.$validators.guardpostCheck = function(value) {
// Is valid if the current value has been validated
return value === validatedValue;
};
ctrl.$validators.guardpost = function(value) {
// Prevent the validator from running twice
if (value !== validatedValue) {
validatedValue = value;
// Only run this validator if the email syntax is valid
if (!ctrl.$error.required && !ctrl.$error.email) {
// Guardpost doc:
// http://documentation.mailgun.com/api-email-validation.html
$http.get(MAILGUN_BASE_URL + '/v2/address/validate', {
params: {
address: value,
api_key: MAILGUN_API_KEY
}
}).success(function(data, status, headers, config) {
// Check is the view value hasn't changed. If it is the case
// an other validation is already in progress and this one
// doesn't matter anymore.
if (ctrl.$viewValue === config.params.address) {
if (status === 200) {
if (data.is_valid === true) {
// Email is valid
isValid = true;
} else {
// Email is not valid
isValid = false;
// If a suggestion is present as part of the response,
// add it to the model to be displayed
ctrl.suggestion = data.did_you_mean ?
data.did_you_mean : null;
}
} else {
// Fail safe, consider email valid on failure.
isValid = true;
}
ctrl.$validate();
}
}).error(function(data, status, headers, config) {
// Fail safe, consider email valid on failure
if (ctrl.$viewValue === config.params.address) {
isValid = true;
ctrl.$validate();
}
});
}
}
// Is valid if the current value has been validated && is valid
return (value === validatedValue) && isValid;
};
}
};
});
@evaflow
Copy link

evaflow commented Nov 8, 2015

how do i use this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment