Curriculum
Course: AngularJS
Login

Curriculum

AngularJS

AngularJS Tutorial

0/65
Text lesson

Custom Validation

Creating your own validation function is a bit more complex; you need to add a new directive to your application and handle the validation within a function that accepts specific arguments.

Example

Create your own directive that includes a custom validation function, and reference it using my-directive. The field will be considered valid only if the value contains the character “e.”

<form name=”myForm”>
<input name=”myInput” ng-model=”myInput” required my-directive>
</form>

<script>

var app = angular.module(‘myApp’, []);
app.directive(‘myDirective’function() {
  return {
    require: ‘ngModel’,
    link: function(scope, element, attr, mCtrl) {
      function myValidation(value) {
        if (value.indexOf(“e”) > –1) {
          mCtrl.$setValidity(‘charE’true);
        } else {
          mCtrl.$setValidity(‘charE’false);
        }
        return value;
      }
      mCtrl.$parsers.push(myValidation);
    }
  };
});
</script>

Example Explained:

In HTML, reference the new directive using the attribute my-directive. In JavaScript, begin by creating a directive named myDirective. Remember to use camel case (myDirective) for naming the directive, while invoking it requires a hyphen-separated name (my-directive). Then, return an object indicating that ngModel is required, representing the ngModelController. Create a linking function that accepts several arguments, with the fourth argument, mCtrl, being the ngModelController. Define a function called myValidation that takes one argument, the input element’s value, and checks if it contains the letter “e,” setting the model controller’s validity accordingly. Finally, use mCtrl.$parsers.push(myValidation); to add the myValidation function to the array of functions that will execute each time the input value changes.