Search code examples
angularjsvaldr

How to dynamically assign valdr rules?


Forgive my minimal knowledge of AngularJS and valdr...

I have an application using AngularJS where the ui is dynamically generated to edit some object with meta-data provided to determine the type to interpret the members of the object. I'm going to add extra meta-data to set validation rules for each member.

I found valdr and I wondered if it might be possible to add the rules using valdrProvider.addConstraints() called repeatedly for each editable field. Presumably the rule names would have to be made unique?

How could I remove rules from the rule set when data was unloaded?

Is this approach valid or should I just map the rule meta data directly using an AngularJS directive or something?


Solution

  • Your approach sounds ok. valdr offers a removeConstraint(constraintName) function that might do what you need. Note, however, that this removes all contraints for a given model type.

    Take the example at https://github.com/netceteragroup/valdr#getting-started.

    yourApp.config(function(valdrProvider) {
      valdrProvider.addConstraints({
        'Person': {
          'lastName': {
            'size': {
              'min': 2,
              'max': 10,
              'message': 'Last name must be between 2 and 10 characters.'
            },
            'required': {
              'message': 'Last name is required.'
            }
          },
          'firstName': {
            'size': {
              'min': 2,
              'max': 20,
              'message': 'First name must be between 2 and 20 characters.'
            }
          }
        }
    });
    

    Calling removeConstraint('Person') would remove all constraints for Person. If you just want to remove the firstName because you remove the first name input field you can call addConstraints again with an updated constraints definition for Person.

    Final notes:

    • valdr doesn't impose you remove constraints if fields are removed (see discussion at https://github.com/netceteragroup/valdr/issues/46)
    • yes, constraint names are unique because they are bound to model types which should have unique names, there shouldn't be two Person types with different implementation