Autocomplete require select
Attribute require on field requires autocomplete input field to contain text, but it does not require user to select a value (from list).
It would be nice to be able to have attribute like select-required and later check for error with ng-messages.
Because of that i often have to do checks like form.$valid && selectedField !== null
+1
This limitation also makes it hard to report that the value entered is not a valid choice. Since the text field is populated, the required validation passes except that the model is invalid.
As a workaround I add:
<input type="hidden" name="hiddenSelectedItem" ng-model="selectedItem" required />
<ng-messages for="form.hiddenSelectedItem.$error" ng-if="form.searchField.$touched && searchText">
<ng-message when="required">Invalid choice</ng-message>
</ng-messages>
With a caveat that the floating label and input border don't turn red.
I came up with a patch that works well enough for my use-case case: it clears the search field when the user leaves it in a dirty state (a value that's not one of the valid choices). Thanks to the clearing the "required" validators can kick in so the user is notified that he didn't pick a valid choice. My workaround with the hidden field (https://github.com/angular/material/issues/4400#issuecomment-141373774) is still needed so the form doesn't appear as valid while the user is typing something.
I don't think this patch can be integrated as-is but hopefully it can help whomever investigate this issue.
diff --git a/www/assets/js/autocomplete.js b/www/assets/js/autocomplete.js
index 1b05402..6911eda 100644
--- a/www/assets/js/autocomplete.js
+++ b/www/assets/js/autocomplete.js
@@ -161,10 +161,15 @@ function MdAutocompleteCtrl ($scope, $element, $mdUtil, $mdConstant, $mdTheming,
$attrs.$observe('required', function (value) { ctrl.isRequired = angular.isString(value) || value; });
$scope.$watch('searchText', wait ? $mdUtil.debounce(handleSearchText, wait) : handleSearchText);
$scope.$watch('selectedItem', selectedItemChange);
+ $scope.$watch(invalidSearch, function(newValue) { if (newValue) { ctrl.scope.searchText = '' }; });
angular.element($window).on('resize', positionDropdown);
$scope.$on('$destroy', cleanup);
}
+ function invalidSearch () {
+ return !ctrl.loading && !hasFocus && !noBlur && !!ctrl.scope.searchText && !ctrl.scope.selectedItem;
+ }
+
/**
* Removes any events or leftover elements created by this controller
*/
+1
+1
+1
@ThomasBurleson this has a pull request #8344