ngUnique
The ngUnique directive allow to verify against a backend service, if the submitted value already exists.
HTML
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>My AngularJS App</title>
</head>
<body ng-controller="stageController">
<div id="main">
<h1>Form validation: {{title}}</h1>
<form name="myForm">
<label for="username">Username:</label>
<br/>
<input type="text" name="username" ng-model="username" ng-pattern="/^[a-zA-Z0-9]{4,10}$/"
ng-unique="tableDB.userDBField" />
<!-- The ngUnique directive take as argument the name of the table, and the column of the database, against which we wanna check the unicity of the submitted value -->
<div class="invalid" ng-show="myForm.username.$dirty && myForm.username.$invalid">Error:
<br/> <span ng-show="myForm.username.$error.pattern">Pattern validation fails.<br/></span>
<span
ng-show="myForm.username.$error.unique">Username already exists.</span>
</div>
</form>
</div>
</body>
</html>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script> <style> #main {
font-size:14px;
padding:15px 10px;
}
h1 {
font-size:18px;
font-weight:bold;
margin:0 0 20px;
}
input {
font-size:12px;
padding:2px 5px;
width:180px;
}
.invalid {
color:red;
margin-top:10px;
}
JavaScript
'use strict';
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.directives']);
/* Controllers */
function stageController($scope) {
$scope.title = 'ngUnique';
$scope.username = '';
}
/* Directives */
angular.module('myApp.directives', [])
.directive('ngUnique', ['$http', function (async) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
elem.on('blur', function (evt) {
scope.$apply(function () {
/*
var val = elem.val();
var req = { "username":val, "dbField":attrs.ngUnique }
var ajaxConfiguration = { method: 'POST', url: 'backendServices/checkUsername.php', data: req };
async(ajaxConfiguration)
.success(function(data, status, headers, config) {
ctrl.$setValidity('unique', data.status);
});
*/
/*
* I should use the code in the above section in a real scenario.
* The file backendServices/checkUsername.php contains the logic to query the DB,
* and verify the unicity of the submitted value.
*
* The following is a mock to show the behaviour in this fiddle.
*/
/* jsFiddle demo */
var ajaxConfiguration = { method: 'POST', url: '/echo/json', data: '{ "status": false }' };
// change to true if you want to test the positive case
async(ajaxConfiguration)
.success(function (data, status, headers, config) {
var obj = JSON.parse(config.data);
...