UI Bootstrap Typeahead: Make input invalid if no option is selected

3.2k views Asked by At

I am using a validation plug-in based on jQuery validation in my AngularJS app (which is built on top of a jQuery library).

The category input (search field) is required. But if I fill it with text and don't select a matching search I can still submit it because there is text in the search field. How can I make it invalid if no option is selected?

Plunkr:

http://plnkr.co/edit/ZYP58GxITghkTqE7PNHy

HTML (help.html)

<div class="form-group">
        <label for="category">Category "{{formData.category}}"</label>
          <input class="form-control" type="text" name="category" id="category" placeholder="Search..." ng-model="formData.category" typeahead="obj.name for obj in getCdOnCat($viewValue)" typeahead-editable="false" typeahead-loading="loadingLocations" required>
    </div>

JS (script.js) - HelpController

//Typeahead: Category Search
    $scope.getCdOnCat = function (searchVal) {
        return dataFactory.getCdOnCategory(searchVal).then(function (response) {
            return response.data.categories;
        }, function (error) {
            console.log('Error: dataFactory.getCdOnCategory');
        });
    };

    $scope.$watch('formData.category', function (value) {
        if (value === "No matching categories") {
            $scope.formData.category = "";
        }
    });
1

There are 1 answers

0
sylwester On

You can add ng-disabled directive to your Submit input

<div class="form-actions">
  <input type="submit" value="Send" class="btn btn-primary btn-submit" ng-disabled="contactForm.$invalid">
</div>

Please see here working demo:

http://plnkr.co/edit/GoOiNmyQ1LSvWvtkqumF?p=preview