dman
dman

Reputation: 11064

Angular.js required and ng-required not working for <textarea></textarea>

I can not get Angular.js required or ng-required to work. I want it to where if the user hits ok, they have to have some text in the textbox.

<div class="modal-body">
    <p>Your change will be logged. Please provide a ticket number or comment for reference</p>
    <div class="row">
        <div class="span4">
            <textarea type="text" class="form-control" 
                ng-model="commentBox.text" 
                ng-required="commentBox.text">
            </textarea>
        </div>
    </div>
</div>

Scratching my head.....

Upvotes: 6

Views: 32341

Answers (2)

harishr
harishr

Reputation: 18065

two things:

  1. make sure that value you are passing to ng-required is boolean (to be technically correct, it should evaluate to boolean)

     <textarea type="text" class="form-control" 
        ng-model="commentBox.text" 
        ng-required="commentBox.textRequired">
    </textarea>
    
    //somewhere in your controller
    $scope.commentBox.textRequired = true
    
  2. you would need form.$invalid on your button

    <button type="submit" ng-disabled="formname.$invalid" ng-click="onsubmit()"></button>
    

so to complete it

   <ng-form name="exampleForm">
     <textarea type="text" ng-model="commentBox.text" ng-required="true"></textarea>
     <button ng-disabled="exampleForm.$invalid" ng-click="onsubmit()"></button>
   </ng-form>

Upvotes: 14

doug31415
doug31415

Reputation: 275

also without adding another prop, you could set it to ng-required="!!commentBox.text"

Upvotes: 2

Related Questions