Search code examples
javascriptangularjshtml-selectangularjs-ng-optionsangularjs-ng-pattern

Smaller Work around for ng-pattern on Select


I am working on an angular app and I needed to put a pattern validation on a select element. Just using ng-pattern on select didn't work. So I created a hidden input with same model with ng-pattern on the hidden input, that didn't work either. So I created a text input with the ng-pattern and hid it via css. Which works beautifully.

Is there a smaller work around for this?

EDIT1: I think I should have added that the options are generated by ng-options

EDIT2: Edited the code snippet accordingly to show what I actually want.

function formCtrl($scope) {
  $scope.options = ['Please Select','Value 1','Value 2'];
  $scope.price = 'Please Select';
    $scope.onSubmit = function (form) {
        console.log(form.$valid);
    }
}
.show-none {
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
    <form name="myForm" ng-submit="onSubmit(myForm)">
        <select ng-model="price" ng-options="o as o for o in options"></select>
        <input type="text" class="show-none" ng-pattern="/^(?!.*(Please Select))/" ng-model="price" name="price_field"> <span ng-show="myForm.price_field.$error.pattern">Not a valid option!</span>

        <input type="submit" value="submit" />
    </form>
</div>


Solution

  • You shouldn't use ng-pattern with hidden input field for this case, you should add value for each option, & then you should have required attribute make sure any of the option should selected before submiting. Adding name="price" will add form element to myForm object.

    Markup

    <select ng-model="price" name="price" required>
         <option>Please Select</option>
         <option value="TEST1">TEST1</option>
         <option value="TEST2">TEST2</option>
    </select>
    

    Update

    If you wanted to make it using ng-options then it would be something like below. You don't need to add Please Select in your array, you could add it manually inside select

    Markup

    <form name="myForm" ng-submit="onSubmit(myForm)" novalidate>
      <select ng-model="price" ng-options="o for o in options" required>
        <option value="">Please select a person</option>
      </select>
    
      <input type="submit" value="submit" />
    </form>
    

    Code

    (function(angular) {
      'use strict';
      angular.module('staticSelect', [])
        .controller('formCtrl', ['$scope', function formCtrl($scope) {
          $scope.options = ['Value 1', 'Value 2'];
    
          $scope.onSubmit = function(form) {
            console.log(form.$valid);
          }
        }]);
    })(window.angular);
    

    Demo here