The end of the more and more lazy, Angularjs study fell for some time, blog has not been updated recently. Ashamed ~ Some time ago have tried to build angular project with yeoman, feel almost like to do a project to practice practiced hand, who met a series of problems. Yeoman is a set of tools based on Node. js, because I have been programming under windows, and Node. JS supports the Windows environment slowly, so try to build a project under Windows with Yeoman. Process far more bumpy than imagined, a variety of error, a variety of search data to solve problems, and ultimately can not solve some of the compilation error, to fail, and fought Linux. It is also a reminder that if you want to use Yeoman under windows, be cautious!
Today to learn about the forms validation that I've been ignoring. Ng's strengths are the development of crud applications, which are more user-intensive and more Interactive. Forms are an important part of interacting with users, so never ignore Them. After learning that this part of the knowledge is not only imagined so simple, compared to other features, we have been very little attention to form validation, in fact, can also be done very simple, and easy to Maintain. Let's start Here.
Forms and controllers in Ng
Look at this little headline. you will be different, form verification, How to relate to the Controller. The form in Ng is different from the form tag we usually use, and it has been enhanced. form is an example of Formcontroller . How to understand this sentence? Think about the scenario where we use the Ng-controller directive:
<div ng-controller= "testc" > <input type= "test" ng-model= "a"/></div><scritp>function TESTC ($scope) { //...}..} </script>
The div that applied Ng-controller is an example of testc, and we can use any of the properties and methods defined on $scopt in the template, and the definition of TESTC is also implemented by Ourselves. When we use <form> is the same reason, formcontroller is defined by NG for us, there are a series of properties and methods to provide us with the validation work, the form instance is identified by the name property, This identity allows us to access the properties and methods of the form instance, such as:
<form name= "myform" >{{myform. $valid}}</form>
The properties provided by form are used to represent the validation status of the form, including: $pristine (the form does not fill in a record), $dirty (the form has a record filled in), $valid (through validation), $invalid (failed validation), $error (validation error message). In addition to $error, the first four values are true or FALSE to indicate the corresponding State. The value of $error is a JS object that contains the status of the following validation content:
email
max
maxlength
min
minlength
number
pattern
required
url
This is what we'll see in a later Example. Formcontroller also provides methods that we generally do not invoke by hand, and are called by the system itself. Refer to the official documentation: Http://docs.angularjs.org/api/ng.directive:form.FormController
Form elements, such as input, checkbox, radio, and so on, are not normal form elements, they are all examples of ngmodelcontroller. As with form, it is also identified by the name Property. Formcontroller owns the five properties, Ngmodelcontroller also has, in addition, there are many additional properties and methods, we will also show in the example, can refer to the official document: http://docs.angularjs.org/ Api/ng.directive:ngmodel.ngmodelcontroller
Another feature needs to know that a form element in a form is automatically added as a property of the form and can be accessed through the name identifier, such as:
<form name= "myform" > <input type= "text" name= "myname"/> {{myform.myname. $valid}}</form >
NG Built-in validation rules
The NG framework provides a very handy validation mechanism, and you just need to add instructions on the label, like using HTML5 provided validation, and then define the Correct/wrong style in the CSS according to the rules, for example, we want a text box to be required and use required:
<form name= "myform novalidate> <input type=" text "ng-model=" a "required/></form>
There are a few points to note:
- A novalidate was added to <form> to disable browser default authentication behavior because NG has already handled several new forms of HTML5 Features.
- Form elements must have ng-model, otherwise validation cannot be triggered
- The four styles of. ng-pristine,. ng-valid,. ng-invalid,. ng-dirty are defined separately in css, and Ng is automatically styled according to the corresponding State.
This part is quite simple, let's write an example to test these verification mechanisms, the HTML code is as Follows:
<div ng-app= "MyApp" ><div ng-controller= "testc" > <form name= "myform" novalidate> required: <input Type= "text" name= "test1" ng-model= "test1" required><br/> ng-minlength (3): <input type= "text" name= "test2" ng-model= "test2" ng-minlength= "3" ><br/> ng-maxlength (ten): <input type= "text" name= "test3" ng-model= "test 3 "ng-maxlength=" ><br/> ng-pattern (/[a-f]/): <input type= "text" name= "test4" ng-model= "test4" Ng-patte rn= "/[a-f]/" ><br/> type= "number" (2-8): <input type= "number" name= "test5" max= "8" min= "2" ng-model= "test5" ><br/> type= "url": <input type= "url" name= "test6" ng-model= "test6" ><br/> type= "email": <in Put type= "email" name= "test7" ng-model= "test7" ><br/> </form> <div> CSS code that sets a different background color for different states:
Input.ng-pristine { background-color:white;} Input.ng-dirty { background-color:lightyellow;} Input.ng-valid { background-color:lightgreen;} Input.ng-invalid { background-color:pink;}
JS code to initialize the Controller:
var app = Angular.module (' MyApp ', []); app.controller (' testc ', function ($scope) { $scope. test1= "; $scope. test2= '; $scope. test3= '; $scope. test4= '; $scope. test5= '; $scope. test6= '; $scope. test7= ';});
The results are as follows:
The example is written on runjs, and click View HTTP://RUNJS.CN/CODE/GSPVLFRW
In the code above, you also see the properties I accessed from the Formconroller instance myform, as well as the properties accessed from Ngmodelcontroller. These properties are very useful, for example, you can add a button to a form: ng-disabled= "myform. $invalid" so that the Submit button is always unavailable when the form is not validated. In addition, according to the form element of these properties, to control the specific error message, such as the wrong mailbox, let "please enter the correct mailbox" this line of words to show out, if you follow my thinking, should be able to imagine Immediately.
Custom validation RulesIn addition to the built-in validation rules, you can define them yourself. The method is to write an instruction that is added to the form Element. Sounds simple, but this command and general instructions can be different, we need to follow certain rules to write, so that can be integrated into NG verification mechanism, so that you can customize the same as the built-in easy to work and Management. At this point, the method provided by Ngmodelcontroller comes in Handy. Let's start with an example.
I want my input box to allow only an even number of inputs, so let's define a directive called even-num, which is used on the page like This:
<input type= "number" ng-model= "test1" even-num/>
The complete JS code is as Follows:
var app = Angular.module (' MyApp ', []); app.controller (' testc ', function ($scope) { $scope. test1 = ";}); App.directive (' evennum ', function () { return { require: ' Ngmodel ', link:function (scope, elm, attrs, Ctrl) { ctrl. $parsers. Push (function (viewvalue) { if (viewvalue% 2 = = 0) { ctrl. $setValidity (' evennum ', true); return viewvalue; } else { ctrl. $setValidity (' evennum ', false); return viewvalue;});};} );
Operation Result:
The above example is written on runjs, click to view HTTP://RUNJS.CN/CODE/GDQ8M0GB
Now let's explain the code Above. How to customize instructions if you are unfamiliar, you can first look at the custom instructions section I wrote earlier. Because our instructions rely on ngmodelcontroller, so write Require: ' Ngmodel ', pay attention to the way of Writing. In addition, in the link function, we use CTRL to refer to the Ngmodelcontroller we injected, and then push a function into its $parsers Property. What is this $parsers? Obviously it's an array, because we can push things in. Before we explain it, we know the two concepts: we put the data in the template, like {{aa}}, called viewvalue, hence the name, the data in the VIEW. We call the data in the model/controller, called Modelvalue. The two-way binding, ng says, is to bind the Two. This $parsers holds the handler functions from the Viewvalue to the Modelvalue binding process, which in the future will be executed sequentially. Because our validation starts with user input, that is, the view has changed, so our validation logic is Here. In the validation results, we call Ctrl. $setValidity method to save the results so that the framework can do the next series of Work.
In contrast to $parsers, there is also a property called $formatters, which holds the handler function from the Modelvalue to the Viewvalue binding process. The validation function that we define, do you want to push into the $formatters too? It depends on your needs. If you're not sure what the difference is, see the following example:
The above example is written on runjs, click to view http://runjs.cn/code/9vde2r0w
The ng-model of two input points to the same, so the data will change synchronously, but there is no push in the $formatters to validate the function, so in the process of binding from Modelvalue to viewvalue, the copy is not Validated. If the validation function is push into the $formatters, then the copy is Validated.
customizing form elementsAs we all know, using Ng-model on form elements allows for two-way binding. But two-way binding can only be used for input, checkbox on these standard form controls, you give a div plus ng-model is not two-way binding, because the system does not know how to bind. so, in order to give the non-standard form control two-way binding, the code has to write their own, it is clear that the custom of a Directive. In fact, this part of the content in the custom directive is also appropriate, but the official website is mentioned here, I also come to Introduce.
We start directly from the example, we must have seen the adaptive text area, that is, as the input content increases, will automatically become higher TEXTAREA. With <textarea> tags, you need to add JS code to Achieve. Better is a pure CSS scheme, using HTML5 's new attribute contenteditable, with a div to simulate the text area, div height By default is adaptive, just to meet the NEEDS. The basic HTML code and CSS code are as Follows:
<style>.smarttextarea{ width:400px; min-height:100px; max-height:400px; border:1px solid; overflow:auto; padding:5px 10px 20px;} </style><div contenteditable= "true" class= "smarttextarea" ></div>
What we're going to do now is that the simulated text area, like the real textarea, can have two-way binding of the data so that it can be verified. I have defined a directive called smarttextarea, which is used like this:
<smarttextarea contenteditable= "true" class= "smarttextarea" ng-model= "test3" required></smarttextarea>
The directive is defined as Follows:
App.directive (' smarttextarea ', function () { var link = function (scope, elm, attrs, ctrl) { //view=>model Data binding elm.bind (' keyup ', function () { scope. $apply (function () { ctrl. $setViewValue (elm.html ()); }); //model=>view Data binding ctrl. $render = function () { elm.html (ctrl. $viewValue); }; Ctrl. $setViewValue (elm.html ()); }; return { template: ' <div></div> ', replace:true, require: ' ngmodel ', restrict: ' E ', Link:link };});
Look at the Effect:
The above example is written on runjs, click to view HTTP://RUNJS.CN/CODE/LHYSP5VH
I gave the simulated textarea added required verification, can be found to be Effective. In fact, the key code is the two-way binding processing of the data, including a couple of steps:
- Bind from view to model, listen for the KeyUp event, and then call Ctrl. $setViewValue method to save Viewvalue
- From model to view binding, call Ctrl. $render method to render viewvalue to the page
With these two steps, we have customized the same elements as the standard form controls, which can be used for two-way binding of the data, and there is no problem with the form Validation.
Reprint: http://www.cnblogs.com/lvdabao/p/3533585.html
Step into Angularjs form and form verification