echo_salik echo_salik - 1 year ago 135
Javascript Question

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


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) {

.show-none {

<script src=""></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" />


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.


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


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


<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>

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


(function(angular) {
  'use strict';
  angular.module('staticSelect', [])
    .controller('formCtrl', ['$scope', function formCtrl($scope) {
      $scope.options = ['Value 1', 'Value 2'];

      $scope.onSubmit = function(form) {

Demo here