彻底弄懂angularJS表单验证

常用的表单验证指令 (基本概念)

1. 必填项验证

某个表单输入是否已填写,只要在输入字段元素上添加HTML5标记required即可:

<input type="text" required />  

2. 最小长度

验证表单输入的文本长度是否大于某个最小值,在输入字段上使用指令ng-minleng= "{number}":

<input type="text" ng-minlength="5" /> 

3. 最大长度

验证表单输入的文本长度是否小于或等于某个最大值,在输入字段上使用指令ng-maxlength="{number}":

<input type="text" ng-maxlength="20" />

4. 模式匹配

使用ng-pattern="/PATTERN/"来确保输入能够匹配指定的正则表达式:

<input type="text" ng-pattern="/[a-zA-Z]/" /> 

5. 电子邮件

验证输入内容是否是电子邮件,只要像下面这样将input的类型设置为email即可:

<input type="email" name="email" ng-model="user.email" /> 

6. 数字

验证输入内容是否是数字,将input的类型设置为number:

<input type="number" name="age" ng-model="user.age" /> 

7. URL

 验证输入内容是否是URL,将input的类型设置为 url:

<input type="url" name="homepage" ng-model="user.facebook_url" />

我们使用了 ng-show指令, color:red 在邮件是 $dirty 或 $invalid 才显示:

属性描述
$dirty 表单有填写记录
$valid 字段内容合法的
$invalid 字段内容是非法的
$pristine 表单没有填写记录

 

示例(以邮箱为例+正则表达式 引入angular+bootstrap)

ng正则表达式写法:

ng-pattern=" /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/"  //邮箱验证

<body  ng-Controller="MyController">  //ng-app标在html标签上
<div class="col-md-6">
  <form role="form" name="myForm" ng-submit="submitForm(myForm.$valid)" class="form-horizontal" novalidate>
    <div class="form-group  has-feedback">
      <div class="col-md-4">
        <label for="email"> 电子邮件</label>
      </div>
      <div class="col-md-6">
        <input type="email" id="email" name="email" ng-minlength="5" ng-maxlength="30" ng-pattern=" /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/" ng-model="user.email" required class="form-control" />
        <span class="glyphicon glyphicon-ok form-control-feedback"
              ng-show="myForm.email.$dirty && myForm.email.$valid"></span>

      </div>
      <div class="col-md-2">
        <span style="color:red" class=""
              ng-show="myForm.email.$dirty && myForm.email.$invalid">邮箱格式错误!</span>
      </div>
    </div>
     <div class="form-group  text-center">
      <input class="btn btn-primary btn-lg" ng-disabled="myForm.$invalid" type="submit" value="提交" />
    </div>
  </form>
</div>

<script>
  angular.module('myTest', [])
          .controller('MyController', function($scope) {
                    $scope.submitForm = function(isValid) {
                      if (!isValid) {
                        alert('验证失败');
                      }
                    };
                  }
          );
</script>
</body>

 


也可以更详尽的支出单个错误:

<div ng-show="myForm.email.$dirty && myForm.email.$error.maxlength" class="alert alert-danger help-block">
          邮箱长度不能超过30位
</div>
<div ng-show="myForm.email.$dirty && myForm.email.$error.minlength" class="alert alert-danger help-block">
          邮箱长度不能小于5位
</div>
<div ng-show="myForm.email.$dirty && myForm.email.$error.email" class="alert alert-danger help-block">
          邮箱格式不正确
</div>

 

  

 

posted @ 2016-10-18 11:46  墨纸瀚云  阅读(257)  评论(0编辑  收藏  举报