查看: 1987|回复: 0

[DIV/CSS] 简单的angular表单验证

发表于 2018-2-28 08:04:09

html:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Angular QuickStart</title>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <link rel="stylesheet" href="styles.css">
  8. <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  9. <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
  10. <script src="http://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script>
  11. <script src="all.js"></script>
  12. </head>
  13. <body ng-app="myApp" class="ng-scope" ng-controller="signUpController">
  14. <form name="signUpForm" ng-submit="submitForm()">
  15. <div class="form-group" ng-class="{'has-warning':signUpForm.username.$invalid && signUpForm.username.$touched}">
  16. <label class="control-label" for="inputWarning">用户名 <br><span ng-if="signUpForm.username.$invalid && signUpForm.username.$touched">您的输入有误请检查</span></label>
  17. <input name="username" id="inputWarning" class="form-control" ng-model="userdata.username" ng-minlength="5" ng-maxlength="10" required/>
  18. </div>
  19. <div class="form-group" ng-class="{'has-warning':signUpForm.password.$invalid && signUpForm.password.$touched}">
  20. <label class="control-label" for="inputWarning1">密码 <br><span ng-if="signUpForm.password.$invalid && signUpForm.password.$touched">您的输入有误请检查</span></label>
  21. <input name="password" id="inputWarning1" class="form-control" ng-model="userdata.password" ng-minlength="5" ng-maxlength="10" required/>
  22. </div>
  23. <div class="form-group" ng-class="{'has-warning':signUpForm.passwordConfirm.$invalid && signUpForm.passwordConfirm.$touched}">
  24. <label class="control-label" for="inputWarning2">确认密码 <br><span ng-if="signUpForm.passwordConfirm.$invalid && signUpForm.passwordConfirm.$touched">您两次输入的密码不一致</span></label>
  25. <input name="passwordConfirm" id="inputWarning2" class="form-control" ng-model="userdata.passwordConfirm" compare="userdata.password" required/>
  26. </div>
  27. <input class="btn btn-primary" type="submit"/>
  28. </form>
  29. </div>
  30. </body>
  31. </html>
复制代码

js:

  1. var App=angular.module('myApp',[]);
  2. App.controller('signUpController',function($scope){
  3. $scope.userdata={};
  4. $scope.submitForm=function(){
  5. console.log($scope.userdata);
  6. }
  7. })
  8. .directive('compare',function(){
  9. var o={};
  10. o.strict='AE'
  11. o.scope={
  12. orgText:'=compare'
  13. }
  14. o.require='ngModel';
  15. o.link=function(sco,ele,att,con){
  16. con.$validators.compare=function(v){
  17. return v==sco.orgText;
  18. }
  19. sco.$watch('orgText',function(){
  20. con.$validate();
  21. })
  22. }
  23. return o;
  24. })
复制代码


回复

使用道具 举报