Home  >  Article  >  Web Front-end  >  AngularJS implements manual form verification and automatic form verification_AngularJS

AngularJS implements manual form verification and automatic form verification_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:26:361187browse

There are roughly two types of form validation in AngularJS, one is manual validation and the other is automatic validation.
1. Manual verification
The so-called manual verification is to verify through the attributes of the AngularJS form. To become an AngularJS form, two conditions must be met:

1. Add novalidate="novalidate" to the form element;

2. Add name="theForm" to the form element, as follows:

<!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}}
   

● Adding novalidate="novalidate" to the form means that the form will no longer use the HTML5 validation feature
● Adding name="theForm" to the form means that the name of the form is theForm. How to use theForm, for example, we verify whether the form has been modified theForm.$submitted
● Submit the form through ng-submit
● formModel is an attribute in $scope
● Manually verified the email of the form, using many properties of the AngularJS form, such as theForm.email.$valid, theForm.$pristine, theForm.$submitted, theForm.email.$error.required, theForm.email.$ error.email
● Print out all attributes of the AngularJS form throughe03b848252eb9375d56be284e690e873{{theForm | json}}bc5574f69a0cba105bc93bd3dc13c4ec

{
 "$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
 }
}

Above, all inputs with name attributes are displayed above.
The module, controller and method of submitting the form are defined in the second.js file.

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);
  };
});

The advantage of the above form verification method is that it is highly controllable, but it is relatively cumbersome.
2. Automatic verification
Another form verification method of AngularJS is automatic verification, which is implemented through directives. In addition to the directives that come with AngularJS, you also need to use the third-party module angular-auto-validate.
About angular-auto-validate:
● Installation: npm i angular-auto-validate
● Quote: b4e9f4e8d58ad62774aad8e6d2549ab22cacc6d41bbb37262a98f745aa00fbf0
● module dependency: var myApp = angular.module("app", ["jcs-autoValidate"]);
In order to localize error messages, the third-party module angular-localize is also needed:
● Installation: npm install angular-localize --save
● module dependency: var myApp = angular.module("app", ["localize"]);
● Quote:

<script src="../node_modules/angular-sanitize/angular-sanitize.min.js"></script>
<script src="../node_modules/angular-localize/angular-localize.min.js"></script>

In addition, when you click the submit form button, you need to disable the button and display a waiting effect. You need to use the third-party module angular-ladda:

● Installation: bower install angular-ladda --save
● module dependency: var myApp = angular.module("app", ["angular-ladda"]);
● Quote:

<link rel="stylesheet" href="../bower_components/ladda/dist/ladda-themeless.min.css"/>

<script src="../bower_components/ladda/dist/spin.min.js"></script>
<script src="../bower_components/ladda/dist/ladda.min.js"></script>
<script src="../bower_components/angular-ladda/dist/angular-ladda.min.js"></script>

The page is as follows:

<!DOCTYPE html>
<html lang="en" ng-app="myApp1">
<head>
 <meta charset="gb2312">
 <title></title>
 <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css"/>
 <link rel="stylesheet" href="../bower_components/ladda/dist/ladda-themeless.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 Validating Auto</a>
  </div>
 </div>
</nav>
 
<div class="container main-content" ng-controller="myCtrl1">
 <!--novalidate让表单不要使用html验证-->
 <!--theForm变成scope的一个字段-->
 <form ng-submit="onSubmit()" novalidate="novalidate">
  <div class="form-group">
   <label for="name" class="control-label">Name</label>
   <input type="text" class="form-control" id="name" ng-model="formModel.name" required="required"/>
  </div>
 
  <div class="form-group">
   <label for="email" class="control-label">Email</label>
   <input type="email" class="form-control" id="email" ng-model="formModel.email" required="required"/>
 
  </div>
 
  <div class="form-group">
   <label for="username" class="control-label">Username</label>
   <input type="text"
       class="form-control"
       id="username"
       ng-model="formModel.username"
       required="required"
       ng-pattern="/^[A-Za-z0-9_]{1,32}$/"
       ng-minlength="7"
       ng-pattern-err-type="badUsername"
    />
  </div>
 
  <div class="form-group">
   <label for="age" class="control-label">Age</label>
   <input type="number"
       class="form-control"
       id="age"
       ng-model="formModel.age"
       required="required"
       min="18"
       max="65"
       ng-min-err-type="tooYoung"
       ng-max-err-type="tooOld"
    />
  </div>
 
  <div class="form-group">
   <label for="sex" class="control-label">Sex</label>
   <select name="sex" id="sex" class="form-control" ng-model="formModel.sex" required="required">
    <option value="">Please choose</option>
    <option value="male">Mail</option>
    <option value="femail">Femail</option>
   </select>
  </div>
 
  <div class="form-group">
   <label for="password" class="control-label">Password</label>
   <input type="text" class="form-control" id="password" ng-model="formModel.password" required="required" ng-minlength="6"/>
  </div>
 
  <div class="form-group">
   <!--<button class="btn btn-primary" ng-click="onSubmit()">Register</button>-->
   <button class="btn btn-primary"
       ladda = "submitting"
       data-style="expand-right"
       type="submit">
    <span ng-show="submitting">正在注册...</span>
    <span ng-show="!submitting">注册</span>
   </button>
  </div>
 
   <pre class="brush:php;toolbar:false">
    {{formModel | json}}
   
<script src="../node_modules/angular-sanitize/angular-sanitize.min.js"></script> <script src="../node_modules/angular-localize/angular-localize.min.js"></script>

For the above, look at the submit button first:

<div >
 <!--<button class="btn btn-primary" ng-click="onSubmit()">Register</button>-->
 <button class="btn btn-primary"
     ladda = "submitting"
     data-style="expand-right"
     type="submit">
  <span ng-show="submitting">正在注册...</span>
  <span ng-show="!submitting">注册</span>
 </button>
</div>

● The ladda attribute value is a bool value. true means that the dynamic waiting effect is displayed, false does not display the dynamic waiting effect. Submitting here is an attribute in the scope
● data-style="expand-right" means to display dynamic waiting effect on the right side of the button

Let’s take the Age field in the form as an example:

<div >
 <label for="age" class="control-label">Age</label>
 <input type="number"
     class="form-control"
     id="age"
     ng-model="formModel.age"
     required="required"
     min="18"
     max="65"
     ng-min-err-type="tooYoung"
     ng-max-err-type="tooOld"
  />
</div>

Among them, min, max are the directives of AgularJS, and ng-min-err-type is the directive of angular-auto-validate. The convention followed here is the directive name -err-type of ng-AngularJS form validation. What are the functions of tooYoung and tooOld, and where are they used?
It is used at the module level and is defined in the form_validation_auto.js file.

var myApp1 = angular.module('myApp1',['jcs-autoValidate','localize','angular-ladda']);
 
myApp1.run(function(defaultErrorMessageResolver){
  defaultErrorMessageResolver.getErrorMessages().then(function(errorMessages){
    errorMessages['tooYoung'] = '年龄必须小于{0}';
    errorMessages['tooOld'] = '年龄不能大于{0}';
    errorMessages['badUsername'] = '用户名只能包含数字、字母或下划线';
  });
});
 
myApp1.controller('myCtrl1', function($scope, $http){
  $scope.formModel = {};
  $scope.submitting = false;
 
  $scope.onSubmit = function(){
 
    $scope.submitting = true;
    console.log('已提交');
    console.log($scope.formModel);
 
    $http.post('url',$scope.formModel)
      .success(function(data){
        console.log(':)');
        $scope.submitting = false;
      })
      .error(function(data){
        console.log(':(');
        $scope.submitting = false;
      });
  };
});

Above, use the defaultErrorMessageResolver service of angular-auto-validate in the run method to customize the error message. tooYoung and tooOld on the page correspond to errorMessages['tooYoung'] and errorMessages['badUsername'] here.

The entire content of this article is introduced here. I hope it will be helpful for you to learn AngularJS to implement form verification.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to dynamically create and submit a form using JavaScript_javascript skillsNext article:How to dynamically create and submit a form using JavaScript_javascript skills

Related articles

See more