关闭

angular表单验证

标签: angular表单验证
261人阅读 评论(0) 收藏 举报
分类:

angular表单验证主要涉及以下指令

  • name:表单字段的属性名
  • ng-pattern:正则表达式
  • ng-required:必填
  • required:必填
  • ng-minlength:最小长度
  • ng-maxlength:最大长度
  • ng-trim:是否自己裁掉头尾空白,默认为true
看例子:
<!DOCTYPE html>
<html ng-app="app">
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <title></title>
  <script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script>
</head>
<body>
  <div ng-controller="ctrl1">
    <form name="myForm">
      <input ng-pattern="/^[0-9]{5}$/" name="fieldA" placeholder="5个数字" ng-model="myData.fieldA"/>
      <input ng-required="true" name="fieldB" placeholder="必填" ng-model="myData.fieldB"/>
      <input ng-minlength="5" name="fieldC" placeholder="最少5个字符" ng-model="myData.fieldC"/>
      <input ng-maxlength="5" name="fieldD" placeholder="最多5个字符" ng-model="myData.fieldD"/>
      <button ng-disabled="myForm.$invalid">提交</button>
    </form>
    <div>
      <div>fieldA error:{{myForm.fieldA.$error}}</div>
      <div>fieldB error:{{myForm.fieldB.$error}}</div>
      <div>fieldC error:{{myForm.fieldC.$error}}</div>
      <div>fieldD error:{{myForm.fieldD.$error}}</div>
      <div>myForm.$error.required = {{!!myForm.$error.required}}</div>
      <div>myForm.$error.minlength = {{!!myForm.$error.minlength}}</div>
      <div>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</div>
      <div>myForm.$error.pattern = {{!!myForm.$error.pattern}}</div>
    </div>
  </div>
  <script>
    var app = angular.module('app',[]);
    app.controller('ctrl1',['$scope',function($scope){
      debugger;
    }])

  </script>
</body>
</html>

form一定要有name属性,这样angular才会给$scope加入myForm属性。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:77667次
    • 积分:1643
    • 等级:
    • 排名:千里之外
    • 原创:88篇
    • 转载:16篇
    • 译文:0篇
    • 评论:0条
    文章分类