Skip to content

Instantly share code, notes, and snippets.

@robhurring
Created October 9, 2014 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robhurring/5e577590df4ae9c6dc76 to your computer and use it in GitHub Desktop.
Save robhurring/5e577590df4ae9c6dc76 to your computer and use it in GitHub Desktop.
Custom form validators with angular
<form name="form">
<label>
Password
<input
type="password"
name="password"
ng-model="password"
required>
</label>
<small class="error" ng-show="form.password.$invalid">
Please enter a password
</small>
<label>
Password Confirmation
<input
type="password"
name="passwordConfirmation"
ng-model="passwordConfirmation"
validate-with="passwordMatcher(value)"
validate-with-name="passwordMatch"
ng-disabled="!account.password"
required>
</label>
<small class="error" ng-show="form.passwordConfirmation.$invalid">
You password confirmation does not match!
</small>
{{ form.passwordConfirmation.$error.passwordMatch }}
</form>
/* global angular */
(function(module) {
'use strict';
// SEE: related SO articles
// http://stackoverflow.com/questions/14012239/password-check-directive-in-angularjs
// http://stackoverflow.com/questions/15060035/invalidate-form-by-custom-component-angularjs
module.directive('validateWith', function() {
return {
require: 'ngModel',
scope: {
validateWith: '&',
validateWithName: '@',
},
link: function(scope, elm, attrs, ctrl) {
scope.validateWithName = scope.validateWithName || 'validateWith';
var handler = function(value) {
var isValid = scope.validateWith({value: value});
ctrl.$setValidity(scope.validateWithName, isValid);
return isValid ? value : undefined;
};
ctrl.$parsers.unshift(handler);
}
};
});
})(angular.module('Auto'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment