Skip to content

Creating your own re usable custom validation directives

Nelson Omuto edited this page Apr 11, 2015 · 1 revision

This is the best way, the angular way to augment your code and add your own custom validation directives.

There is only one step involved as opposed to the 4 step process of the old method. :)

In an app config block, simply inject the myValidationsProvider and add your array of customValidations:

YourApp.config(function (myValidationsProvider) {
    myValidationsProvider.addCustomValidations([
       {
          customValidationAttribute: 'validationOnlyAlphabets',
          errorMessage: 'Valid characters are: A-Z, a-z',
          validateWhileEntering: true,
          validator: function (errorMessageElement, val){
              return (/^[a-z]*$/i).test(val);
          }
     },
     {
          customValidationAttribute: 'validationOneUpperCaseLetter',
          errorMessage: 'Must contain at least one uppercase letter',
          validator: function (errorMessageElement, val){
             return (/^(?=.*[A-Z]).+$/).test(val);
          }
     }
   ]);
});

By passing in the model, model controller, scope, directive attribute(rawAttr), etc. Your validator function will have access to all the variables pertinent to ensuring maximum flexibility. The signature for the validator function is shown below: function (errorMessageElement, val, attr, $element, model, ngModelController, $scope, rawAttr) {}