Loading

angularjs的表单验证

angularjs内置了常用的表单验证指令,比如min,require等。下面是演示:

<!DOCTYPE html>
<html>
    <head>
          <meta charset="UTF-8">
    </head>
    <body ng-app="app" ng-controller="ctrl" >
        <style>
            .valid-error{
                color:red
            }
        </style>
        <form name="form" novalidate>
             <input type="text" ng-model="value0" required name="input0">
             <span class="valid-error" ng-show="form.input0.$error.required">
                        值必须输入
            </span>
            <input type="number" ng-model="value1" min="0" name="input1">
             <span class="valid-error" ng-show="form.input1.$error.min">
                        值必须大于等于0
            </span>
        </form>
    </body>
    <script src="bower_components/angular/angular.js">
    </script>
    <script>
        var app = angular.module('app',[]);
        app.controller('ctrl',function($scope){
            $scope.value0='1';
            $scope.value1=0;
        });
    </script>
</html>

  

我们也可以自定义一个验证指令,比如验证电话号码的。

   <input type="text" ng-model="phoneNum"  name="phoneNum" phone>
             <span class="valid-error" ng-show="form.phoneNum.$error.phone">
                       电话号码不合法
            </span>

  

 var PHONE_REGEXP = /(^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$/;    
app.directive('phone', function () { return { require: 'ngModel', link: function (scope, elm, attrs, ctrl) { ctrl.$validators.phone = function (modelValue, viewValue) { if (ctrl.$isEmpty(modelValue)) { // consider empty models to be valid return true; } if (PHONE_REGEXP.test(viewValue)) { // it is valid return true; } // it is invalid return false; }; } }; });

posted @ 2016-08-26 16:52  Agile.Zhou  阅读(263)  评论(0编辑  收藏  举报