how to invalidate a form when using directive in a

2019-08-11 06:18发布

问题:

i am working on a SPA and a form inside this app uses an input masked text box implemented using a third party library from here

i created a directive to set a mask for an IP address

angular
.module('app').directive('ipMask', [
    function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function (scope, element, attrs, ngModel) {        
                    element.mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
                    element.mask('099.099.099.099');

                    scope.$watch(attrs.ngModel, function (newValue, oldValue) {
                        //????????
                    });
            }
        };
    }
]);

where my form code looks like

    <div ng-controller="nodesListCtrl as vm">
        <form role="form" name="frmNode">

            <div class="form-group">
                <label>Node IP :</label>
                <input type="text" data-ip-mask ng-model="vm.myIp" name="CtrIp" class="input-sm form-control" placeholder="..." >
            </div>
        </form>
    </div>

i want to invalidate the form if the IP address is wrong. i.e. i am expecting .ng-invalid class both on the form and and the control as well until the time it remains invalid. any suggestions ?

回答1:

You don't need to use $watch. Just add a parser and/or formatter. Parsers are called when the view changes and formatters when the model changes. (This link can tell you more about those, as well as the other things available on ngModelController: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController). Here's an example:

link: function (scope, element, attrs, ngModel) {        
  element.mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
  element.mask('099.099.099.099');

  ngModel.$parsers.unshift(function(value) {
    var valid = isValid(value); // made up - use whatever validation technique based on that library
    ngModel.$setValidity('ip', valid);
    return valid;
  });

  ngModel.$formatters.unshift(function(value) {
    var valid = isValid(value);
    ngModel.$setValidity('ip', valid);
    return valid ? value : undefined;
  });
}