0

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.

1 Answer 1

1

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.

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

3 Comments

You cannot do === in the template with angular. Also it would be simpler to just check if the field has a value ng-required="author" and ng-required="keyword" respectfully.
Wait, is it possible to just include Ng-require="author || keyword" to get the behavior I want for this form? How would one extract that type of behavior into a directive?
I don't know about not being able to do === in a template, but just do ==. I use that all the time and it works fine

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.