继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

简单的angular表单验证

SOHO树叶
关注TA
已关注
手记 56
粉丝 61
获赞 656

html:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script src="http://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script>
    <script src="all.js"></script>
  </head>

  <body ng-app="myApp" class="ng-scope" ng-controller="signUpController">
    <form name="signUpForm" ng-submit="submitForm()">
        <div class="form-group" ng-class="{'has-warning':signUpForm.username.$invalid && signUpForm.username.$touched}">
          <label class="control-label" for="inputWarning">用户名 <br><span ng-if="signUpForm.username.$invalid && signUpForm.username.$touched">您的输入有误请检查</span></label>
          <input name="username" id="inputWarning" class="form-control" ng-model="userdata.username" ng-minlength="5" ng-maxlength="10" required/>
        </div>
      <div class="form-group" ng-class="{'has-warning':signUpForm.password.$invalid && signUpForm.password.$touched}">
        <label class="control-label" for="inputWarning1">密码 <br><span ng-if="signUpForm.password.$invalid && signUpForm.password.$touched">您的输入有误请检查</span></label>
        <input name="password" id="inputWarning1" class="form-control" ng-model="userdata.password" ng-minlength="5" ng-maxlength="10" required/>
      </div>
      <div class="form-group" ng-class="{'has-warning':signUpForm.passwordConfirm.$invalid && signUpForm.passwordConfirm.$touched}">
        <label class="control-label" for="inputWarning2">确认密码 <br><span ng-if="signUpForm.passwordConfirm.$invalid && signUpForm.passwordConfirm.$touched">您两次输入的密码不一致</span></label>
        <input name="passwordConfirm" id="inputWarning2" class="form-control" ng-model="userdata.passwordConfirm" compare="userdata.password" required/>
      </div>
      <input class="btn btn-primary" type="submit"/>
    </form>
  </div>
  </body>
</html>

js:

var App=angular.module('myApp',[]);
App.controller('signUpController',function($scope){
      $scope.userdata={};
      $scope.submitForm=function(){
        console.log($scope.userdata);
      }
})
.directive('compare',function(){
    var o={};
    o.strict='AE'
    o.scope={
      orgText:'=compare'
    }
    o.require='ngModel';
    o.link=function(sco,ele,att,con){
        con.$validators.compare=function(v){
          return v==sco.orgText;
        }
        sco.$watch('orgText',function(){
            con.$validate();
        })
    }
    return o;
})
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP