Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Following is my code snippet. I want to validate my dropdown using angular.

<td align="left" width="52%"> 
  <span class="requiredSmall">*</span> 
    <select class="Sitedropdown" style="width: 220px;" 
            ng-model="selectedSpecimen().serviceID" 
            ng-options="service.ServiceID as service.ServiceName for service in services"> 
         <option value="" ng-selected="selected">Select Service</option> 
   </select> 
</td>

Valid means:

Valid values can be anything but "Select Service", it is my default value. Like other ASP.net Require field validator DefaultValue="0" for dropdown, so here My dropdown will be bound from the services and I want to select all other values except "Select Service".

share|improve this question
up vote 87 down vote accepted

You need to add a 'name' attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

<form name="myForm" ng-controller="Ctrl">

  <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> 
  <span ng-show="myForm.service_id.$error.required">Select service</span>

</form>

Controller:

function Ctrl($scope) {
  $scope.services = [
    {ServiceID: 1, ServiceName: 'Service1'},
    {ServiceID: 2, ServiceName: 'Service2'},
    {ServiceID: 3, ServiceName: 'Service3'}
  ];
}

Here's a working plunker.

share|improve this answer
4  
It should be mentioned that select needs ng-model for this to work – phikes Aug 26 '13 at 10:21
1  
Correct, ngOptions require ngModel. – Stewie Aug 26 '13 at 11:38
    
this example is so useful. thanks you. – ddagsan Jun 10 at 15:26

protected by T J May 23 at 7:42

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.