Created
October 9, 2014 19:00
-
-
Save robhurring/5e577590df4ae9c6dc76 to your computer and use it in GitHub Desktop.
Custom form validators with angular
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
<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> |
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
/* 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