Skip to content

Instantly share code, notes, and snippets.

@ShMcK
Created September 30, 2014 10:26
Show Gist options
  • Save ShMcK/221e883157f1caef5b26 to your computer and use it in GitHub Desktop.
Save ShMcK/221e883157f1caef5b26 to your computer and use it in GitHub Desktop.
Using Angular 1.3 Forms with $validators, ngMessages, $pending, $touched Src: http://www.htmlxprs.com/post/11/angularjs-1.3-form-validation-tutorial
<html ng-app="demoApp">
<script type="text/javascript">
angular.module('demoApp', ['ngMessages']); // include ngMessages module
angular
.module('htmlxprs', [])
.directive('usernameValidator', function () {
return {
restrict: 'AE',
require: 'ngModel',
link: function ($scope, elem, attrs, ngModel) {
ngModel.$validators.username = function (modelValue, viewValue) {
var value = modelValue || viewValue;
return /^[a-zA-Z0-9]+$/.test(value);
};
}
};
})
.directive('usernameAvailability', function () {
return {
restrict: 'AE',
require: 'ngModel',
link: function ($scope, elem, attrs, ngModel) {
ngModel.$asyncValidators.usernameAvailability = function (modelValue, viewValue) {
var value = modelValue || viewValue;
return usernameService.checkAvailability(value);
};
}
};
});
</script>
<body ng-controller="validatorCtrl">
<form name="demoForm">
Username:
<!-- $validator: username-validator checks if available-->
<input type="text" name="username" ng-model="username" username-validator ng-required="true"/>
<!-- $pending: display message while validating (!exists & proper characters -->
<span ng-show="demoForm.username.$pending">Checking Availability . . .</span>
<!-- Show messages with ngMessages when $touched || submitted -->
<div class="messages" ng-messages="demoForm.username.$error"
ng-if="demoForm.username.$touched || demoForm.$submitted">
<div class="error-message" ng-message="required">Username is required.</div>
<div class="error-message" ng-message="username">Username must contain only letters and numbers.</div>
<div class="error-message" ng-message="usernameAvailability">Sorry! The username has been taken.</div>
</div>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment