var angular = angular.module('plunker', []);
angular.controller('MainCtrl', function($scope) {
});
angular.directive("phoneValidator", function () {
return {
require : 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, ngModel) {
ngModel.$validators.phone = function(value) {
return !value || /0[\d]{9}/.test(value);
};
}
};
});
angular.directive("uniqueUsernameValidator", function ($q, $timeout) {
return {
require : 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, ngModel) {
var existingUsernames = ["sebastieno"];
ngModel.$asyncValidators.uniqueusername= function(value) {
if (ngModel.$isEmpty(value)) {
return $q.when();
}
var def = $q.defer();
$timeout(function() {
if (existingUsernames.indexOf(value) === -1) {
// Le username n'existe pas
def.resolve();
} else {
def.reject();
}
}, 2000);
return def.promise;
};
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js" data-semver="1.3.7"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name="form" novalidate>
<div>
Login:
<input type="text" ng-model="name" name="name" unique-username-validator />
<span ng-show="form.name.$pending.uniqueusername">Vérification de la disponibilité du login...</span>
<span ng-show="form.name.$error.uniqueusername">Le login existe déjà</span>
</div>
<div>
Téléphone:
<input type="text" ng-model="phone" name="phone" phone-validator />
<span ng-show="form.phone.$error.phone">Le numéro de téléphone est incorrect</span>
</div>
</form>
</body>
</html>
/* Put your css in here */