所谓手动验证是通过angularjs表单的属性来验证,而成为angularjs表单必须满足两个条件:
1、给form元素加上novalidate=novalidate;
2、给form元素加上name=theform,
如下:
form submitting
name
email 必填
email格式不正确
username
age
sex please choose mail femail
password
register
{{theform | json}}
● 给form加上novalidate=novalidate意味着表单将不再使用html5验证特性 ● 给form加上name=theform意味着表单的名称是theform。如何使用theform,比如我们验证表单是否被修改过theform.$submitted ● 通过ng-submit提交表单 ● formmodel是$scope中的一个属性 ● 对表单的email进行了手动验证,使用了angularjs表单的众多属性,比如theform.email.$valid,theform.$pristine,theform.$submitted, theform.email.$error.required,theform.email.$error.email ● 通过{{theform | json}}
把angularjs表单的所有属性都打印出来{ $error: { 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, $dirty: false, $pristine: true, $valid: false, $invalid: true, $submitted: false, email: { $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 }, sex: { $validators: {}, $asyncvalidators: {}, $parsers: [], $formatters: [], $viewchangelisteners: [], $untouched: true, $touched: false, $pristine: true, $dirty: false, $valid: true, $invalid: false, $error: {}, $name: sex, $options: null }}
以上,凡是有name属性的input都被显示在上面。
在second.js文件中定义了module,controller以及提交表单的方法。
var myapp1 = angular.module('myapp1',[]);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手动表单验证能够熟练操作。