2017-04-21 113 views
0

我有一个表单,它在我的待办事项列表数组中添加项目。 但是,如果输入字段为空,我的函数将为我的数组添加一个空值。使用angularJS验证输入文本

什么是验证表单的最佳方法?

 <form name="formaddtodo" ng-submit="todoList.addTodo()"> 
      <input type="text" ng-model="todoList.todoText" ng-minlength="1" size="30" 
        placeholder="Voeg nieuwe todo toe"> 
      <input class="btn-primary" type="submit" value="voeg toe"> 
     </form> 

这里是我的功能

todoList.addTodo = function() { 
       todoList.todos.push({text:todoList.todoText, done:false}); 
       todoList.todoText = ''; 
     }; 

没有确认,但是我很好奇的最好办法是验证什么。

预先感谢您!

回答

0

您可以使用内置的ngRequired指令:

<input type="text" ng-model="todoList.todoText" ng-minlength="1" size="30" 
     placeholder="Voeg nieuwe todo toe" ng-required="required"> 

AngularJS提供了最常见的HTML5输入 类型的基本实现:(文字,数字,网址,电子邮件,日期,单选,多选) ,以及 验证的一些指令(要求,模式,最小长度,最大长度,最小值,最大值)。

https://docs.angularjs.org/guide/forms

0
<form name="formaddtodo" ng-submit="todoList.addTodo(formaddtodo.$valid)"> 
     <input type="text" ng-model="todoList.todoText" ng-minlength="1" size="30" 
       placeholder="Voeg nieuwe todo toe" required> 
     <input class="btn-primary" type="submit" value="voeg toe"> 
    </form> 


todoList.addTodo = function(isValid) { 
      if(isValid) { 
      todoList.todos.push({text:todoList.todoText, done:false}); 
      todoList.todoText = ''; 
      } 
    }; 

我认为上面的代码会帮助你验证你的表单。

0

ngMessages用于显示信息给用户的表单验证模块支持。

ngMessages,开发人员被迫依靠诸如ng-class和ng-show的指令来显示这些错误。

请按照此link。它可能对您现在和未来用于AngulerJS验证有用。