Skip to content

Instantly share code, notes, and snippets.

@oaleynik
Created March 24, 2014 16:27
Show Gist options
  • Save oaleynik/9743779 to your computer and use it in GitHub Desktop.
Save oaleynik/9743779 to your computer and use it in GitHub Desktop.
Passwords match directive
var myApp = angular.module('myApp', []).directive('uiValidateEquals', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
function validateEqual(myValue, otherValue) {
if (myValue === otherValue) {
ctrl.$setValidity('equal', true);
return myValue;
} else {
ctrl.$setValidity('equal', false);
return undefined;
}
}
scope.$watch(attrs.uiValidateEquals, function(otherModelValue) {
validateEqual(ctrl.$viewValue, otherModelValue);
});
ctrl.$parsers.unshift(function(viewValue) {
return validateEqual(viewValue, scope.$eval(attrs.uiValidateEquals));
});
ctrl.$formatters.unshift(function(modelValue) {
return validateEqual(modelValue, scope.$eval(attrs.uiValidateEquals));
});
}
};
});
<div class="well" ng-controller="MyCtrl">
<form name="form">
<label>e-mail</label>
<input name="email" type="email" required ng-model="email">
<label>repeat e-mail</label>
<input name="emailRepeat" type="email" required ng-model="emailRepeat" ui-validate-equals="email">
<span ng-show='form.emailRepeat.$error.equal'>Both e-mail adresses must match</span>
<hr>
email errors: {{form.email.$error | json}}<br>
emailRepeat errors: {{form.emailRepeat.$error | json}}<br>
</form>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment