Angular: Empty Fiddle
http://angularjs.org/
by sunnycyk
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap.min.css">
<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="{'emailRepeat' : 'assertSame($value, 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>
JavaScript
var myApp = angular.module('myApp', []).directive('uiValidate', ['$parse', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var validateDef = scope.$eval(attrs.uiValidate);
if (angular.isString(validateDef)) {
validateDef = {
validator: validateDef
};
}
angular.forEach(validateDef, function(validatorExpr, key) {
var validateFn = function(valueToValidate) {
var validatorFn = $parse(validatorExpr);
if (validatorFn(scope, {
$value: valueToValidate
})) {
ctrl.$setValidity(key, true);
return valueToValidate;
} else {
ctrl.$setValidity(key, false);
return undefined;
}
};
ctrl.$formatters.push(validateFn);
ctrl.$parsers.push(validateFn);
});
}
};
}]);
function MyCtrl($scope) {
$scope.assertSame = function($value, email) {
console.log($value);
return $value === email;
}
}