Reputation: 7337
We use simple form in our project and now I just created a form which is loaded as an angular template. I would also like to handle validation using angular, but take errors from a response. Do you know any ready to go angular directives for handling validation errors of simple form?
Upvotes: 0
Views: 222
Reputation: 405
Here are the form validation strategy for angularjs forms:
ng-minlength : specify the minimum length of the input text you want
ng-maxlength : specify the maximum length of the input text you want
var app = angular.module('validationExample', []);
app.directive('ensureUnique', ['$http', function($http) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, c) {
scope.$watch(attrs.ngModel, function() {
$http({
method: 'POST',
url: '/api/check/' + attrs.ensureUnique,
data: {'field': attrs.ensureUnique}
}).success(function(data, status, headers, cfg) {
c.$setValidity('unique', data.isUnique);
}).error(function(data, status, headers, cfg) {
c.$setValidity('unique', false);
});
});
}
}
}]);
var app = angular.module('validationExample', []);
app.directive('ensureUnique', ['$http', function($http) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, c) {
scope.$watch(attrs.ngModel, function() {
$http({
method: 'POST',
url: '/api/check/' + attrs.ensureUnique,
data: {'field': attrs.ensureUnique}
}).success(function(data, status, headers, cfg) {
c.$setValidity('unique', data.isUnique);
}).error(function(data, status, headers, cfg) {
c.$setValidity('unique', false);
});
});
}
}
}]);
You can access your form fields in this way
formName.inputFieldName.property
You can check whether form is touched by the user or not
formName.inputFieldName.$pristine;
You can check whether form is touched by the user or not opposite of $pristine
formName.inputFieldName.$dirty
You can check whether form is valid or not
formName.inputFieldName.$valid
Its opposite of $valid
formName.inputFieldName.$invalid
you can also format your form using these class names
.ng-pristine {}
.ng-dirty {}
.ng-valid {}
.ng-invalid {}
Upvotes: 1