0

I want to create a custom form validation, using AngularJS. That form should have input and select elements. The form should be valid, when either imputs are empty or both filled with some values. Here is the view:

<form name="recipientsForm" novalidate>
    <md-input-container>
        <label>Name</label>
        <input name="name" type="text" ng-model="relationship.name" value="" empty-or-both-filled="relationship.relationshipType">
        <div ng-messages="recipientsForm.name.$error">
            <div ng-message="emptyOrBothFilled">Enter name.</div>
        </div>
    </md-input-container>
    <md-input-container>
        <md-select name="type" placeholder="Select your relation... " ng-model="relationship.relationshipType" empty-or-both-filled="relationship.name">
            <md-option ng-repeat="type in relationshipTypes" value="{{type.relationshipType}}">
                {{type.name}}
            </md-option>
        </md-select>
        <div ng-messages="recipientsForm.type.$error">
            <div ng-message="emptyOrBothFilled">Pick relationship.</div>
        </div>
    </md-input-container>
</form>

And here is the directive:

(function () {
    'use strict';

    angular
        .module('app')
        .directive('emptyOrBothFilled', [emptyOrBothFilled]);

    function emptyOrBothFilled() {
        return {
            restrict: 'A',
            required: 'ngModel',
            scope: {
                targetNgModel: '=emptyOrBothFilled'
            },
            link: function($scope, element, attrs, ngModel) {
                ngModel.$validators.emptyOrBothFilled = function(val) {
                    var isValueEmpty = !val;
                    var isTargetEmpty = !$scope.targetNgModel;

                    return (isTargetEmpty && isValueEmpty) || (!isTargetEmpty && !isValueEmpty);
                }

                $scope.$watch('targetNgModel', function() {
                    ngModel.$validate();
                })
            }
        }
    }
})();

Prompt, please, why do I get this error:

TypeError: Cannot read property '$validators' of undefined
    at link (http://localhost:3000/app/shared/directives/EmptyOrBothFilled.js:17:24)

1 Answer 1

1

It should be

require: 'ngModel',

not

required: 'ngModel',

in the directive specification.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.