Last active
March 24, 2017 20:34
-
-
Save bettysteger/0b32be1f7962691556b1 to your computer and use it in GitHub Desktop.
Custom angular form validation (Angular 1.2 vs 1.3)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Angular 1.2 | |
* Helper method for Signup and Update. Checks if email or username of user exists per GET request. | |
* Sets custom validation: 'exists' to true or false. | |
* @example | |
* <input type="email" name="email" ng-model="user.email" ng-change="checkIfExists(form.email)" /> | |
*/ | |
var timeout = false; | |
$scope.checkIfExists = function(input) { | |
if(!input.$viewValue) { return; } | |
var params = {}; | |
params[input.$name] = input.$viewValue; | |
input.$setValidity('exists', true); | |
if(timeout) { | |
$timeout.cancel(timeout); | |
} | |
timeout = $timeout(function () { | |
User.exists(params, function(data) { | |
if(data.exists) { | |
input.$setValidity('exists', false); | |
} | |
}); | |
}, 500); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Angular 1.3 | |
* Helper method for Signup and Update. Checks if email or username of user exists per GET request. | |
* Sets custom validation: 'exists' to true or false. | |
* @example | |
* <input type="email" name="email" ng-model="user.email" user-exists-validator /> | |
*/ | |
app.directive('userExistsValidator', function($q, User) { | |
return { | |
require : 'ngModel', | |
link: function($scope, element, attrs, ngModel) { | |
ngModel.$asyncValidators.exists = function(value) { | |
var defer = $q.defer(); | |
var params = {}; | |
params[attrs.name] = value; | |
User.exists(params, function(data) { | |
if(data.exists) { | |
defer.reject(); | |
} else { | |
defer.resolve(); | |
} | |
}); | |
return defer.promise; | |
}; | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment