基于angularJS的表单验证练习

  今天看了一下angularJS的表单验证,看的有点云里雾里(也有可能是雾霾吸多了),于是做了一个小练习来巩固一下。

html:

<div ng-controller="Aaa">
    <form novalidate name="loginForm">
        <div>
            <label>用户名</label>
            <input type="text" name="nText" ng-model="promptText.name" required ng-pattern="/^[a-zA-Z]+$/" ng-minlength="5" ng-blur="promptText.change(loginForm.nText.$error)"/>
            <span ng-repeat=" pro in promptText.proList | filter:promptText.defaultPro">{{pro.tip}}</span>
        </div>

        <div>
            <label>密码</label>
            <input type="password" name="nPassword" ng-model="promptPassword.name" required ng-pattern="/([a-zA-Z]/w+$)/" ng-minlength="5" ng-blur="promptPassword.change(loginForm.nPassword.$error)"/>
            <span ng-repeat=" pro in promptPassword.proList | filter:promptPassword.defaultPro">{{pro.tip}}</span>
        </div>
    </form>

</div>

js:

var m1=angular.module('myApp',[]);
        m1.controller('Aaa',['$scope',function($scope){
            $scope.promptText={
                defaultPro:'default',
                proList:[
                    {'name':'default','tip':'请输入用户名'},
                    {'name':'required','tip':'用户名不能为空'},
                    {'name':'pattern','tip':'格式不符合规则'},
                    {'name':'minlength','tip':'不得小于5个字符'},
                    {'name':'pass','tip':'正确'}
                ],
                change:function(err){
                    console.log(err);
                    for(attr in err){
                        if(err[attr]==true){
                            this.defaultPro=attr;
                            return;
                        }
                    }
                    this.defaultPro='pass';
                }
            }

            $scope.promptPassword={
                defaultPro:'default',
                proList:[
                    {'name':'default','tip':'请输入密码'},
                    {'name':'required','tip':'密码不能为空'},
                    {'name':'pattern','tip':'以字母开头,只能包含字母、数字、下划线'},
                    {'name':'minlength','tip':'不得小于5个字符'},
                    {'name':'pass','tip':'正确'}
                ],
                change:function(err){
                    console.log(err);
                    for(attr in err){
                        if(err[attr]==true){
                            this.defaultPro=attr;
                            return;
                        }
                    }
                    this.defaultPro='pass';
                }
            }
        }]);

css:

.ng-invalid{
            border:1px solid red;
        }
.ng-valid{
            border:1px solid green;
        }

 

posted @ 2015-12-01 21:22  很好玩  阅读(295)  评论(0编辑  收藏  举报