AngularJS directive for unique email address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
define(['angular', 'app'], function(angular) { 'use strict'; /** * @ngdoc directive * @name ngSeed.directives:ngUnique * @description * Checks if an email is already present in the database. */ angular .module('app.directives') .directive('ngUnique', function($http) { return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { var $elem = $(elem); // Trigger on blur of email input $elem.on('blur', function(evt) { // Check when the email is valid first if (scope.registerForm.email.$valid) { // We're out of Angular here so we need to apply to scope scope.$apply(function() { console.log('checking email is available...'); // Ajax request to check if email is available $http({ method: 'POST', url: '/user/isEmailAvailable', data: { "email": $elem.val(), "dbField": attrs.ngUnique } }). success(function(data, status, headers, config) { console.log('ajax success...' + data.status); // Set email is available/not available. ctrl.$setValidity('unique', data.status); }). error(function(data, status, headers, config) { console.log("ajax fail...(" + status + ")."); ctrl.$setValidity('unique', false); }); }); } }); } } }); }); |
Refs:
https://www.ng-newsletter.com/posts/validations.html
https://blog.brunoscopelliti.com/form-validation-the-angularjs-way
One problem with this code.
If it will set model validity to false (ctrl.$setValidity(‘unique’, data.status);)
it will never again pass the condition:
if (scope.registerForm.email.$valid) {
email model will be always $invalid due to ‘unique’ and so the form will be always $invalid. IMHO the better would be condition:
if (!scope.registerForm.email.$error.required && !scope.registerForm.email.$error.email)
Thanks Krzysztof, yes I will post the full code soon, this was for unique email only.