Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.