AngularJS Input Verification Detailed Explanation and Example Code
- 2021-07-06 09:47:19
- OfStack
AngularJS input validation
AngularJS forms and controls can validate the data entered.
Input validation
In the previous chapters, you have learned about AngularJS forms and controls.
AngularJS forms and controls provide validation and warnings for illegal data entered by users.
Note: Client-side validation cannot ensure the security of user input data, so server-side validation is also necessary.
Application code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<h2> Verification instance </h2>
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<p> User name :<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required"> User name is required. </span>
</span>
</p>
<p> Mailbox :<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required"> Mailbox is a must. </span>
<span ng-show="myForm.email.$error.email"> Illegal email address. </span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = 'john.doe@gmail.com';
});
</script>
</body>
</html>
Run results:
Verification instance
User name:
Mailbox:
Note: The HTML form property novalidate is used to disable browser default authentication.
Instance parsing
The AngularJS ng-model directives are used to bind input elements into the model.
Model objects have two attributes: user and email.
We used the ng-show directive, and color: red is displayed when the message is $dirty or $invalid.
属性 | 描述 |
---|---|
$dirty | 表单有填写记录 |
$valid | 字段内容合法的 |
$invalid | 字段内容是非法的 |
$pristine | 表单没有填写记录 |
The above is the data collation of AngularJS input verification, which will be supplemented in the future, hoping to help students who study.