如何仅允许< input>中的数字0-5 AngularJS的字段? [英] How to only allow the numbers 0-5 in <input> fields with AngularJS?

查看:193
本文介绍了如何仅允许< input>中的数字0-5 AngularJS的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的输入字段:

I have an input field like this:

HTML

<input ng-model="newtodo.effort" ng-enter="addTodo()" type="number" min="0" max="5"
       maxlength="1" size="1" step="1" class="form-control marginBottom"
       placeholder="Aufwand" aria-describedby="basic-addon2" required></input>

JavaScript / Angular controller

$scope.addTodo(todo) {
    restservice.addTodo(todo); // Does call to REST service backend
}

在上面的输入字段中我只想要允许整数值0,1,2,3,4和5.

In the input field above I only want to allow integer values 0, 1, 2, 3, 4 and 5.

允许浮点数(例如1.4),字符(例如foo)和小于0或大于5的值。

Not allowed are floats (e.g. 1.4), characters (e.g. foo) and values less than 0 or bigger than 5.

输入字段可能不为空

正如您所看到的,我已经在使用HTML5输入属性,但我知道我不能依赖它们。另外,如果输入的值对我的限制有效,我也会检查服务器端。到目前为止一切都很好,但为了提高我的Web应用程序的可用性和响应能力,我还想使用AngularJS在JavaScript中验证这些值。我该怎么办?我知道我可以在 $ scope.addTodo(todo)中实现复杂的值检查,如果他/她输入的值不合适,则会向用户输出错误消息我不知何故觉得使用RegEx和1-liner有更好,更容易的棱角分明方式?如果是这样,请向我解释如何以Angular的方式做到这一点。谢谢!

As you can see I am already using HTML5 input attributes for this but I know that I cannot rely on those. Additionally I also check server-side if the values entered are valid against my restrictions. So far so good, but in order to increase usability and responsiveness of my web app I also want to validate these values in JavaScript using AngularJS. How would I do that? I know that I could implement complicated value checks in $scope.addTodo(todo) and then output error messages to the user if the values he/she entered weren't ok but I somehow "feel" that there is a better, easier "angularish" way using RegEx and a 1-liner? If so, please explain to me how to do this the Angular way. Thanks!

推荐答案

您可以将以下属性添加到输入字段。

You can add the following attribute to your input field.

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

并按此验证:

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>

这篇关于如何仅允许&lt; input&gt;中的数字0-5 AngularJS的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆