Skip to content

Instantly share code, notes, and snippets.

@bettysteger
Last active March 24, 2017 20:34
Show Gist options
  • Save bettysteger/0b32be1f7962691556b1 to your computer and use it in GitHub Desktop.
Save bettysteger/0b32be1f7962691556b1 to your computer and use it in GitHub Desktop.
Custom angular form validation (Angular 1.2 vs 1.3)
/**
* 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);
};
/**
* 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