使用angualrJS实现表单的验证功能
和原生js相比减少很多代码量,简化代码,提示信息 简单明了,便于修改和增加验证条件
<script>
angular.module('myApp',['ngMessages']).controller('formController', function ($scope) {
$scope.email = "";
$scope.password = "";
$scope.submitForm = function () {
if($scope.form_1.$valid){
alert('通过验证');
}else{
alert('未通过验证');
}
}
})
</script>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="#" name="form_1" ng-controller="formController" ng-submit="submitForm()">
<div class="form-group">
<label>账号:</label>
<input class="form-control" name="email" ng-model="email"
ng-minlength="8"
ng-maxlength="12" placeholder="请输入账号" required="required">
<span class="error" ng-show="form_1.password.$invalid">
<small ng-show="form_1.email.$error.minlength">账号长度最小为6</small>
<small ng-show="form_1.email.$error.required">请输入账号</small>
<small ng-show="form_1.email.$error.maxlength">账号长度最大为12</small>
</span>
</div>
<div class="form-group">
<label>密码:</label>
<input class="form-control" name="password" ng-model="password"
ng-minlength="10" ng-maxlength="20"
placeholder="请输入密码" required="required"
ng-pattern="/\w/">
<span class="error" ng-show="form_1.password.$invalid">
<small ng-show="form_1.password.$error.minlength">密码长度最小为10</small>
<small ng-show="form_1.password.$error.required">请输入密码</small>
<small ng-show="form_1.password.$error.maxlength">账号长度最大为20</small>
<small ng-show="form_1.password.$error.pattern">密码必须为字母数字下划线组合</small>
</span>
</div>
<div class="form-group">
<input type="submit" value="登录" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>