"Required" validation doesn't work in <select> with default value

Issue

I have a required <select> field:

<select name="service_id" class="Sitedropdown" style="width: 220px;" 
        ng-model="ServiceID" 
        ng-options="service.ServiceID as service.ServiceName for service in services"
        required> 
  <option value="">Select Service</option> 
</select> 

When it is empty, the form should display a “Select service” error message. Here’s a working plunker.

It works fine when you intentionally selects the empty option. But when you reload the page, the service_id is empty by default and there is no validation. How to make AngularJS validate the default value?

Solution

Your code:

ng-show="myForm.service_id.$dirty && myForm.service_id.$invalid

This means – if value is dirty (was changed) and is invalid. Remove first and you’ll get what you want.

Answered By – Petr Averyanov

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.