ng-validator

Angular validation helper class

View project on GitHub

ng-validator

Angular validation helper class

How to install

bower install ng-validator --save

How to use

Include it as dependency

angular.module('myApp', ['ngValidator']);

Inject in Controller / Service / Whatever

AppController.$inject = ['Validator'];

function AppController (Validator) {
  var self = this;

  self.input = {
    title: '',
    description: '',
    agree: null,
    reason: ''
  };

  self.errors = {};

  self.submit = submit;

  var rules = {
    title: 'required',
    description: 'required_with:title',
    agree: 'required',
    reason: 'required_with:title|required_if:agree,0'
  }

  var customMessages = {
    'description.required_with': 'Field needs to be filled if title present',
    'reason.required_with': 'Please provide reason',
    'reason.required_if': 'Please provide reason',
  }

  function submit() {
    self.errors = {};

    var validator = new Validator(self.input, rules, customMessages);

    if (validator.fails()) {
      for (var field in validator.errors.all()) {
          self.errors[field] = validator.errors.first(field);
      };  
    }
  }
}

Show errors in template

<div ng-controller="AppController as app">
  <form ng-submit="app.submit()">
    <div class="form-group" ng-class="{'has-error': app.errors.title}">
      <label class="form-label">Title</label>
      <input class="form-control" ng-model="app.input.title" />
      <span class="help-block" ng-if="app.errors.title" ng-bind="app.errors.title">
    </div>
    <button class="btn btn-primary">Submit</button>
  </form>
</div>

Or wrap it in simple directive

angular
  .module('myApp')
  .directive('inputValidation', inputValidation);

function inputValidation() {
  return {
    restrict: 'E',
    scope: {
      field: '@',
      parent: '='
    },
    templateUrl: 'templates/inputValidation.html',
    link: function (scope, elem, attr) {}
  }
};

Create template

<div class="form-group" ng-class="{'has-error': parent.errors[field]}">
  <label class="form-label" ng-bind="field"></label>
  <input class="form-control" 
         ng-model="parent.input[field]"
         ng-change="parent.errors[field] = null" />
  <span class="help-block" 
        ng-if="parent.errors[field]" 
        ng-bind="parent.errors[field]"></span>
</div>

And use as

<input-validation parent="app" field="title"></input-validation>