Search code examples
cssangularjsvaldr

Angular/Valdr - Add custom classes to valdr-form-group


Im pretty new to Angular. I'm using Valdr for validating my forms in Angular. I want to add some custom classes with my own css on a form-group when there is an error.

In the documentation of Valdr I found this part about CSS to control visibility. It says that I need to inject valdrClasses and override the values. But on every try I get an error. I tried adding it as a module/provider but nothing works.

My code without valdrClasses:

angular.module('validators', ['valdr'])
  .config(function (valdrProvider, valdrMessageProvider) {
    valdrProvider.addConstraints({
      'User': {
        'name': {
          'required': {
            'message': 'Name is required.'
          }
        },
        'email': {
          'required': {
            'message': 'Email is required.'
          },
          'email': {
            'message': 'Must be a valid e-mail address.'
          }
        }
      }
    });

    valdrMessageProvider.setTemplate('<div class="help-block">{{ violation.message }}</div>');

  });

Can someone help me in the right direction? Because I have no clue how to inject and customize the css classes.


Solution

  • Inject the valdr service into for example a controller or in the run block and use the function setClasses.

    For example if you want to only override invalid:

    app.run(function(valdr) {
    
      valdr.setClasses({
        invalid: 'my-invalid-class'
      });
    });
    

    Demo: http://plnkr.co/edit/otLvNqXjRiJ4CGl8gDlu?p=preview

    Note that it might depend on which version of Valdr you are using.