我正在尝试使用angularJS验证一些输入字段。我找到了一些例子。但他们正在验证整个表格。
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" ng-model='name' ng-required="true" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
</div>
和控制器代码是
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name=undefined;
$scope.preview = function(){
alert("Previewed");
};
$scope.update = function(){
alert("Updated");
}
});
以上代码根据表单名称验证字段。但我想知道有没有办法验证特定的输入字段?
答案 0 :(得分:2)
DEMO
是的,您必须为输入指定name
,如
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" name='name' ng-model='name' ng-required="true" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
</div>
然后您可以检查name
是否对myForm.name.$valid
答案 1 :(得分:0)
查看小提琴here。
只需在name
字段中添加input
,然后按照与form
相同的方式进行操作。
<强> HTML:强>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" ng-model='name' ng-required="true" name="txtName" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
<div>Status of name: <span style="color: blue">{{myform.txtName.$valid}}</span></div>
</form>
</div>
<强> JS:强>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.name = undefined;
$scope.preview = function () {
alert("Previewed");
};
$scope.update = function () {
alert("Updated");
}
});