Reputation: 166
I have a form that requires at least one of two fields to have a value in order to be valid. Right now I've built a directive 'keywordAndOrAuthor' to handle the validation for this. I've managed to get it to correctly check if either field has a value and if so set the validation to true. What I'm not sure how to do is to set the validation for the other field to also be true. Here's the current code for the directive:
angular.module('dashboard').directive 'keywordAndOrAuthor', ->
require: "ngModel"
link: (scope, elem, attrs, ctrl) ->
ctrl.$setValidity 'keywordAndOrAuthor', false
ctrl.$parsers.unshift (viewValue) ->
siblingElem = elem.siblings('.keyword, .author')[0]
if viewValue || siblingElem.value
ctrl.$setValidity 'keywordAndOrAuthor', true
viewValue
How can I set the validity of the siblingElem to true?
** EDIT **
Here's a working solution for what I wanted.
$scope.keywordOrAuthor = (topic_source) ->
if (topic_source.authors || topic_source.keywords) then false else true
The key point to realize is that ng-required works similar to Angular ng-class or ng-disable, in that it only adds the required attribute to an element if the condition being evaluated returns true. In other words, in the example above, if there is a value for either the authors parameter or keywords parameter then the function (which is used inside the ng-require directive) will return false, and will then not return a validation error.
Upvotes: 0
Views: 139
Reputation: 1690
Try setting ng-required to be "if the other field is blank"
<input type="text" ng-model="keyword" ng-required="author === undefined">
<input type="text" ng-model="author" ng-required="keyword === undefined">
Then I don't know that you need any of that directive.
Upvotes: 1