0
votes

Let's say we need a custom Angular validator that provides arguments to the error message. For instance if we were to create a validator that would evaluate the minimum length of an array and when it was invalid the message should be "The minimum length is {0}".

Now considering we have created a custom directive(as the one provided below) for this validation, how do we provide the "{0}" argument from the validation directive function to the validation message?

Here's a custom validation directive for the that:

.directive('arrayLength', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$validators.arrayLength = function (modelValue, viewValue) {
                return modelValue >= parseInt(attrs.arrayLength);
            };
        }
    };
});

And here where we would be declaring the message:

.run([
    'defaultErrorMessageResolver',
    function (defaultErrorMessageResolver) {
        defaultErrorMessageResolver.getErrorMessages().then(function (errorMessages) {
            errorMessages['arrayLength'] = 'Minimum length is {0}';
        });
    }
]);

So... any ideas?

I'm sure it's not a rocket science. It's just that I'm new to Angular.

Thanks in advance.

1
A plunker or jsfiddle to use running code? - Ignacio Villaverde
Yes. Here's a fiddle: jsfiddle.net/4tsc7gcf/14 Just hit GO!! and notice the displayed message. the {0} arg is empty. - alvesdm

1 Answers

0
votes

Look this. Can pass the message on the own policy ("messageerror")

var app = angular.module("myApp", []);

function Fiddle($scope) {}

app.directive('input', function() {
    return {
        restrict: 'E',
        scope: {
            minlength: "@minlength"
        },
        link: function(scope, elm, attr, ctrl) {
            
            elm.bind('keyup', function() {
                var valid = (this.value && this.value.length >= scope.minlength);
                if (!valid){
                    if(elm.parent().find("span").length == 0)
                        elm.parent().append("<span style='border:solid 3px #FE2E2E'>Min is " + scope.minlength + "</span>");
                }else
                    elm.parent().find("span").remove();
            });
        }
    };
});
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<form name="myForm" novalidate ng-app="myApp">
  <ul ng-controller="Fiddle">
    <li>
      <label for="barthirty">Min 3 Char:</label>
      <input input-data type="datetime" ng-model="nmTest" minlength="3"/>

    </li>
  </ul>
</form>