ciembor
ciembor

Reputation: 7337

SimpleForm validation and Angular

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

Answers (1)

Yashdeep Hinge
Yashdeep Hinge

Reputation: 405

Here are the form validation strategy for angularjs forms:

  1. ng-minlength : specify the minimum length of the input text you want

  2. ng-maxlength : specify the maximum length of the input text you want

  3. ng-pattern : specify a js regular expression to be checked for validating input text
  4. if you have an api and want to get a unique value in a field than tune in this code snippet

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

Related Questions