Angularjs uses commands for form verification. angularjs forms
Preface
Generallyangular
For form verification, the verification rules are generally writtenservice
And then use the dependency injection method. In some cases, for example, the user registry form, you need to provide different prompts based on user input, useservice
This is slightly inappropriate, so you can use commands.
Simple Form
The following is a simple form with four prompts displayed based on the status. The verification rules are numbers, uppercase letters, and lowercase letters.ng-pattern
The same effect can be achieved. Here, only the instruction verification is introduced. Where,user-validator
Is a custom command.
<Form class = "form-horizontal" name = "form" role = "form" ng-controller = "ValidCtrl"> <div class = "form-group"> <label = "user" class = "col-sm-2 control-label"> user Name </label> <div class = "col-sm-5"> <input type = "text" ng-model = "user" name = "user" id = "user" user-validator class = "form-control" required = "required"> </div> <label class = "col-sm-5" ng-show = "form. user. $ pristine "> enter the username </label> <label class =" col-sm-5 "ng-show =" form. user. $ error. required & form. user. $ dirty "> User name cannot be blank </label> <label class =" col-sm-5 "ng-show =" form. user. $ error. defined & form. user. $ dirty "> username does not comply with the rules </label> <label class =" col-sm-5 "ng-show =" form. user. $ valid & form. user. $ dirty "> valid username </label> </div> </form>
Verification command
The verification command code is as follows:
angular.module('shuffleApp', []) .directive('userValidator', ['$log', function($log) { return { restrict: 'A', require: 'ngModel', link: function($scope, $element, $attrs, $ngModelCtrl) { var verifyRule = [/^\d+$/, /^[a-z]+$/, /^[A-Z]+$/]; var verify = function(input) { return !(verifyRule[0].test(input) || verifyRule[1].test(input) || verifyRule[2].test(input)); }; $ngModelCtrl.$parsers.push(function(input) { var validity = verify(input); $ngModelCtrl.$setValidity('defined', validity); return validity ? input : false; }); $ngModelCtrl.$formatters.push(function(input) { var validity = verify(input); $ngModelCtrl.$setValidity('defined', validity); return validity ? input : false; }) } } }]);
The command content is very simple. check whether all the commands are numbers, lowercase letters, and uppercase letters. Then, obtain the verification result by taking the reversed command. Then, set the verification result in $ parser and $ formatter.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.