AngularJS ng-message directive always showing message

279 Views Asked by At

I am trying to set the select field in the view to be required. So I'm having the below tags in my view.html

<form name="homeForm">
  <div class="form-group col-md-6 md-padding">
    <div>
        <label style="font-size: medium">Laboratory Name</label>
        <select name="labName" class="form-control" ng-model="request.labName" required>
            <option ng-repeat="lab in labList" value="{{lab.id}}">{{lab.value}}</option>
        </select>
        <div style="color:maroon" ng-messages="homeForm.labName.$error"
             ng-if="homeForm.requestTypeName.$touched">
            <div ng-message="required">This field is required</div>
        </div>
    </div>

I was hoping the This field is required will show up only when there is no data selected. But irrespective of the field has data or not This field is required shows up like below enter image description here

Is there something I am missing here

3

There are 3 best solutions below

0
georgeawg On BEST ANSWER

The ng-messages directive is in a separate library module and must be included as a dependency.

Example

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/angular-messages/angular-messages.js"></script>

JS

angular.module("app",["ngMessages"])

For more information, see AngularJS ngMessages Module API Reference.

5
Victor On

You are using homeForm.requestTypeName in the ng-if, and there is no input control named requestTypeName, i guess you must use homeForm.labName as you use in the ng-message attribute.

Basically, change the ng-if to ng-if="homeForm.labName.$touched"

TL;DR;

You could use as well the homeForm.labName.$error.required for checking if actually the end user has passed away that field without entering some input.

Source: https://docs.angularjs.org/api/ng/directive/ngRequired

2
yBrodsky On

You need to set the same input name in your input and in your ng-message. Doing this, you don't even need to have ng-if. For example:

<form name="form">
  <input name="fullname" type="text" ng-model="fullname" required/>
  <div ng-messages="form.$submitted && form.fullname.$error">
    <p ng-message="required" class="help-block">This field is required</p>
  </div>
</form>

In this case I am using form.$submitted. You can remove that, replace it with touched/dirty or whatever. The principle is the same.