Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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.....

like image 561
dman Avatar asked Aug 01 '14 16:08

dman


People also ask

How to add required field in Angular?

AngularJS ng-required DirectiveThe ng-required directive sets the required attribute of a form field (input or textarea). The form field will be required if the expression inside the ng-required attribute returns true. The ng-required directive is necessary to be able to shift the value between true and false .

What is Ng-required in AngularJS?

The ng-required Directive in AngularJS is used to specify the required attribute of an HTML element. The input field in the form is required only if the expression inside the ng-required directive returns true. It is supported by <input>, <select> and <textarea> tags.

What is NG model?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.


2 Answers

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>
like image 84
harishr Avatar answered Nov 09 '22 12:11

harishr


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

like image 2
doug31415 Avatar answered Nov 09 '22 10:11

doug31415