AngularJS手动表单验证

前端之家收集整理的这篇文章主要介绍了AngularJS手动表单验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

所谓手动验证是通过AngularJS表单的属性来验证,而成为AngularJS表单必须满足两个条件:

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

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

如下:

<Meta charset="UTF-8">

<div class="container main-content" ng-controller="myCtrl1">

<form ng-submit="onSubmit(theForm.$valid)" novalidate="novalidate" name="theForm">
<div class="form-group">
<label for="name">Name
<input type="text" class="form-control" id="name" ng-model="formModel.name"/>

<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
<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 class="help-block" ng-show="theForm.email.$error.email && (!theForm.$pristine || theForm.$submitted)">email格式不正确

<div class="form-group">
<label for="username">Username
<input type="text" class="form-control" id="username" ng-model="formModel.username"/>

<div class="form-group">
<label for="age">Age
<input type="number" class="form-control" id="age" ng-model="formModel.age"/>

<div class="form-group">
<label for="sex">Sex
<select name="sex" id="sex" class="form-control" ng-model="formModel.sex">
<option value="">Please choose
<option value="male">Mail
<option value="femail">Femail

<div class="form-group">
<label for="password">Password
<input type="text" class="form-control" id="password" ng-model="formModel.password"/>

<div class="form-group">
<button class="btn btn-primary" type="submit">Register

  {{theForm | json}}
  
required": [ { "$validators": {},"$asyncValidators": {},"$parsers": [],"$formatters": [ null ],"$viewChangeListeners": [],"$untouched": true,"$touched": false,"$pristine": true,"$dirty": false,"$valid": false,"$invalid": true,"$error": { "required": true },"$name": "email","$options": null } ] },"$name": "theForm","$submitted": false,"email": { "$validators": {},"$formatters": [ null ],"$error": { "required": true },"$options": null },"sex": { "$validators": {},"$formatters": [],"$valid": true,"$invalid": false,"$error": {},"$name": "sex","$options": null } }

以上,凡是有name属性的input都被显示在上面。

在second.js文件中定义了module,controller以及提交表单的方法

myApp1.controller('myCtrl1',function($scope,$http){
$scope.formModel = {};

$scope.onSubmit = function(){
$http.post('someurl',$scope.formModel)
.success(function(data){
console.log(':)');
})
.error(function(data){
console.log(':(');
});

console.log($scope.formModel);
};
});

以上的表单验证方式好处是可控性强,但相对繁琐。

以上就是本文的全部内容,希望对AngularJS手动表单验证能够熟练操作。

AngularJS手动表单验证

猜你在找的JavaScript相关文章