如何使用angularjs验证特定的输入字段?

时间:2016-02-23 09:24:42

标签: html angularjs validation

我正在尝试使用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");
    }
});

以上代码根据表单名称验证字段。但我想知道有没有办法验证特定的输入字段?

2 个答案:

答案 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");
    }
});