How to only allow the numbers 0-5 in <input> fields with AngularJS?

前端 未结 2 1183
无人及你
无人及你 2021-01-21 23:52

I have an input field like this:

HTML



        
相关标签:
2条回答
  • 2021-01-22 00:41

    You can use ngPattern to set the regular expression which you want to validate against.

    Reffer to the docs for more details: https://docs.angularjs.org/api/ng/directive/input

    0 讨论(0)
  • 2021-01-22 00:45

    You can add the following attribute to your input field.

    ng-pattern="/^[0-5]+$/" 
    

    And validate as such:

    function formCtrl($scope) {
    
    }
    <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">
        <input type="number" ng-model="newtodo.effort" name="effort" ng-pattern="/^[0-5]$/" ng-enter="addTodo()" step="1" class="form-control marginBottom" placeholder="Aufwand" aria-describedby="basic-addon2" required>
        <span ng-show="myForm.effort.$error.pattern">The number must be between 0-5</span>
        <span ng-show="myForm.effort.$error.number">No characters allowed</span>
        <span ng-show="myForm.effort.$error.required && !myForm.effort.$error.number">The field is required</span>
      </form>
    </div>

    0 讨论(0)
提交回复
热议问题