简体   繁体   English

如何验证动态生成的文本框?

[英]How to do validation for dynamically generated textboxes?

I am developing a web application in AngularJS . 我正在AngularJS开发一个Web应用程序。 I am generating some textboxes dynamically. 我正在动态生成一些文本框。 I want to do validation for each of the generated textboxes. 我想对每个生成的文本框进行验证。

Below is my html where I am generating textboxes. 以下是我在其中生成文本框的html。

<div ng-repeat="text in Textboxes">
    <input class="with-icon" type="text" name="{{text.name}}" required value="{{text.value}}"/>
</div>

Below is my JS code. 以下是我的JS代码。

$scope.Textboxes = [{ name: 'name1', value: 'value1' }, { name: 'name2', value: 'value2' }];

Whenever I click on submit button if I did not enter anything in text boxes then I want to make textboxes red. 每当我未在文本框中输入任何内容时,单击“提交”按钮,则我希望将文本框设置为红色。

Can it be done for dynamically generated textboxes? 可以为动态生成的文本框完成此操作吗?

  1. Use ng-model instead of value 使用ng-model代替value
  2. use a ng-class or ng-style to conditionally (hence check with the text.value ) add some style to make it red 使用ng-classng-style有条件地(因此检查text.value )添加一些样式使其变为红色
  3. use $invalid in the form to check whether all text field are validated with text entry or not, apply something (may be disabled) to submit button look and feel or in click event (prevent the action according to $invalid in the form) 在表单中使用$invalid来检查是否所有文本字段均已通过文本输入验证,应用某些内容(可能被禁用)以提交按钮外观或单击事件(根据表单中的$invalid阻止操作)

use form to validate the submit 使用form来验证提交

 angular.module("app",[]) .controller("ctrl",function($scope){ $scope.Textboxes = [{ name: 'name1', value: 'value1' }, { name: 'name2', value: 'value2' }] }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> <form name="loginform"> <div ng-repeat="text in Textboxes"> <input class="with-icon" type="text" name="{{text.name}}" required value="{{text.value}}"/> </div> <button type="submit" >Login</button> </form> </div> 

Use ng-model to bind the values and then ng-class to set/remove error class that changes the border to red/black 使用ng-model绑定值,然后使用ng-class设置/删除将边框更改为红色/黑色的错误

I think This is what you're looking for 我想这就是你要找的

Plunkr 普伦克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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