首页 >web前端 >js教程 >AngularJS实现表单手动验证和表单自动验证_AngularJS

AngularJS实现表单手动验证和表单自动验证_AngularJS

WBOY
WBOY原创
2016-05-16 15:26:361249浏览

AngularJS的表单验证大致有两种,一种是手动验证,一种是自动验证。
一、手动验证
所谓手动验证是通过AngularJS表单的属性来验证。而成为AngularJS表单必须满足两个条件:

1、给form元素加上novalidate="novalidate";

2、给form元素加上name="theForm",如下:

<!DOCTYPE html>
<html lang="en" ng-app="myApp1">
<head>
 <meta charset="UTF-8">
 <title></title>
 <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css"/>
 <link rel="stylesheet" href="../css/main.css"/>
</head>
<body>
<nav >
 <div class="container">
  <div class="navbar-header">
   <a href="/" class="navbar-brand">Form Submitting</a>
  </div>
 </div>
</nav>
 
<div class="container main-content" ng-controller="myCtrl1">
 <!--novalidate让表单不要使用html验证-->
 <!--theForm变成scope的一个字段-->
 <form ng-submit="onSubmit(theForm.$valid)" novalidate="novalidate" name="theForm">
  <div class="form-group">
   <label for="name">Name</label>
   <input type="text" class="form-control" id="name" ng-model="formModel.name"/>
  </div>
 
  <div class="form-group" ng-class="{
   'has-error': !theForm.email.$valid && (!theForm.$pristine || theForm.$submitted),
   'has-success': theForm.email.$valid && (!theForm.$pristine || theForm.$submitted)
   }">
   <label for="email">Email</label>
   <input type="email" class="form-control" id="email" ng-model="formModel.email" required="required" name="email"/>
   <p class="help-block" ng-show="theForm.email.$error.required && (!theForm.$pristine || theForm.$submitted)">必填</p>
   <p class="help-block" ng-show="theForm.email.$error.email && (!theForm.$pristine || theForm.$submitted)">email格式不正确</p>
  </div>
 
  <div class="form-group">
   <label for="username">Username</label>
   <input type="text" class="form-control" id="username" ng-model="formModel.username"/>
  </div>
 
  <div class="form-group">
   <label for="age">Age</label>
   <input type="number" class="form-control" id="age" ng-model="formModel.age"/>
  </div>
 
  <div class="form-group">
   <label for="sex">Sex</label>
   <select name="sex" id="sex" class="form-control" ng-model="formModel.sex">
    <option value="">Please choose</option>
    <option value="male">Mail</option>
    <option value="femail">Femail</option>
   </select>
  </div>
 
  <div class="form-group">
   <label for="password">Password</label>
   <input type="text" class="form-control" id="password" ng-model="formModel.password"/>
  </div>
 
  <div class="form-group">
   <button class="btn btn-primary" type="submit">Register</button>
  </div>
 
   <pre class="brush:php;toolbar:false">
    {{theForm | json}}
   
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn