简体   繁体   中英

ng-disable a button if ng-pattern of input does not match

I want to disable a button with ng-disable if ng-pattern of an input field does not match the regular expression. In this case the regular expression is "[0-9]". I have tried the following code:

Index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml" ng-app="Filter">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ASCII" />
    <title>Test</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
    <script type="text/javascript" src="Test.js"></script>
  </head>
  <body>
      <div class="ctrl" ng-controller="Ctrl">
          Text <input type="text" ng-model="input_field" ng-pattern="[0-9]"><br/>
          <button ng-disabled="input_field.$valid">Start Filter</button>
      </div>
  </body>
</html>

Test.js

Module.controller('Ctrl', function($scope){
    $scope.input_field = "Insert your Text here!";
}

Unfortunately it is not working. I have tried many ways but nothing worked. Do you have any ideas how to disable the button if the pattern do not match.

I think you should wrap it with <form> and fix the syntax: $error instead of $valid , [0-9] -> /^[0-9]/ . Here is a demo, adjust it appropriately:

 <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl"> <form name="myForm"> Input: <input type="text" ng-model="input_field" name="input_field" ng-pattern="/^[0-9]/" placeholder="Insert a number"><br/> <button ng-disabled="myForm.input_field.$error.pattern || !input_field">Start Filter</button> </form> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) {}); </script> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM