Improve this Doc View Source

ngRequired adds the required `validator` to `ngModel`. It is most often used for `input` and `select` controls, but can also be applied to custom controls.

The directive sets the `required` attribute on the element if the Angular expression inside `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we cannot use interpolation inside `required`. See the interpolation guide for more info.

The validator will set the `required` error key to true if the `required` attribute is set and calling `NgModelController.$isEmpty` with the `ngModel.$viewValue` returns `true`. For example, the `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.

## Directive Info

- This directive executes at priority level 0.

## Usage

- as attribute:

      <ANY>
      ...
      </ANY>

## Examples

    <script>
      angular.module('ngRequiredExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.required = true;
        }]);
    </script>
    <div ng-controller="ExampleController">
      <form name="form">
        <label for="required">Toggle required: </label>
        <input type="checkbox" ng-model="required" id="required" />
        <br>
        <label for="input">This input must be filled if `required` is true: </label>
        <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
        <hr>
        required error set? = <code>{{form.input.$error.required}}</code><br>
        model = <code>{{model}}</code>
      </form>
    </div>

    var required = element(by.binding('form.input.$error.required'));
    var model = element(by.binding('model'));
    var input = element(by.id('input'));

    it('should set the required error', function() {
      expect(required.getText()).toContain('true');

      input.sendKeys('123');
      expect(required.getText()).not.toContain('true');
      expect(model.getText()).toContain('123');
    });