Although I am not a front-end programmer, I understand how important it is to validate the front end.
Because the back end can take more breath, and compared to the back end of what really is the front-end can improve the user's happiness.
ANGULARJS provides a convenient form validation feature, which is documented here.
Let's start with the code below.
<form ng-app="myApp" ng-controller="validationController" name="mainForm" novalidate> <p>Email: <input type="email" name="email" ng-model="email" required> <span style="color:red" ng-show="mainForm.email.$dirty && mainForm.email.$invalid"> <span ng-show="mainForm.email.$error.required">Email is required.</span> <span ng-show="mainForm.email.$error.email">Invalid email address.</span> </span> </p> <p> <input type="submit" ng-disabled="mainForm.$invalid"> </p></form><script>angular.module(‘myApp‘,[]).controller(‘validationController‘, [‘$scope‘,function($scope) { $scope.user = ‘Kavlez‘; $scope.email = ‘[email protected]‘;}]);</script>
Some validation options for the input tag, usually paired with the HTML5 tag.
Must fill in
<input type="text" required />
Length
Use Instructions ng-minlength
/ng-maxlength
<input type="text" ng-minlength="5" />
Specific format
For example, e-mail, URL, number, set type to the appropriate type, for example:
<input type="email" name="email" ng-model="user.email" /><input type="number" name="age" ng-model="user.age" /><input type="url" name="homepage" ng-model="user.facebook_url" />
Pattern matching
Use Directives ng-pattern
, such as:
<input type="text" ng-pattern="[a-z]" />
Form properties, which make it easier to manipulate the form
$pristine/$dirty
Indicates whether it has been modified, for example
<form name="mainForm" ng-controller="orderController"><input type="email" name="userEmail" ng-model="myEmail" /> {{mainForm.userEmail.$pristine}} {{mainForm.userEmail.$dirty}}</form>
In Formname.fieldname. $pristine access, input must have a Ng-model declaration.
ANGULARJS provides a CSS class for form status
- . ng-pristine
- . ng-dirty
- . ng-valid
- . ng-invalid
For example, let the validation pass for green, and the failure to red:
input.ng-valid { color: green;}input.ng-invalid { color: green;}
Given the example of just one email verification is written so much, if you add a few more field, add several different hints, plus a few events, the code will become messy.
In fact it is not recommended to do so, we have a better way.
is to use angular-messages.js
First, don't forget these two steps.
OK, first replace those duplicates with ng-messages and ng-message , the example above becomes:
<form ng-controller="validationController" name="mainForm" > <p>Email: <input type="email" name="email" ng-model="myEmail" ng-minlength="3" ng-maxlength="50" required /> <div style="color:red" ng-messages="mainForm.email.$error" ng-messages-multiple> <p class="error" ng-message="required">Email is required.</p> <p class="error" ng-message="email">Invalid email address.</p> <p class="error" ng-message="minlength">min length 10</p> <p class="error" ng-message="maxlength">max length 50</p> </div> </p> <p> <input type="submit" ng-disabled="mainForm.$invalid" /> </p></form>
There is no change in functionality, just removing the duplicated code.
Attention to distinguish ng-messasges
and ng-message
, there is no feeling a bit like with()
? Back ng-messages-multiple
, here is used to let multiple hints appear at the same time.
But this is still not good enough, even if the content is omitted ng-message
, but there are many fields in the existence of required validation will still have duplicates.
And, if the forms in different pages involve the same content, there are more and more repeated validation prompts.
To solve this problem, we can use the ng-messages-include directive.
This directive is used to refer to a template, such as the above example:
<form ng-controller="validationController" name="mainForm" > <p>Email: <input type="email" name="email" ng-model="myEmail" ng-minlength="3" ng-maxlength="50" required /> <div style="color:red" ng-messages="mainForm.email.$error" ng-messages-multiple ng-messages-include="validateTemplate/email.html"> </div> </p> <p> <input type="submit" ng-disabled="mainForm.$invalid" />
It's not complicated, let's add something.
To make the hint more friendly (?) Some, we try to achieve the effect of prompting when the cursor leaves.
This time with the instruction (Directive) will be much more convenient, here first involved a bit and the instruction related content.
Run it up first:
var myApp = angular.module(‘myApp‘,[]) .controller(‘validationController‘, [‘$scope‘,function($scope) { $scope.user = ‘Kavlez‘; $scope.email = ‘[email protected]‘; }]) .directive(‘hintOnBlur‘, [function() { return { require: ‘ngModel‘, link: function(scope, element, attrs, ctrl) { ctrl.focused = false; element.bind(‘focus‘, function(evt) { scope.$apply(function() {ctrl.focused = true;}); }).bind(‘blur‘, function(evt) { scope.$apply(function() {ctrl.focused = false;}); }); } } }]);
Here we use focused
to determine if the cursor is on a property, and the hintOnBlur
state of the object on which the instruction was used occurs focus
or blur
when focused
the status of the event changes.
The form changes as well, using the following method:
<form ng-controller="validationController" name="mainForm" > <p>Email: <input type="email" name="email" ng-model="myEmail" ng-minlength="3" ng-maxlength="50" required hint-on-blur /> <div style="color:red" ng-messages="mainForm.email.$error" ng-show="!mainForm.email.focused" ng-messages-multiple ng-messages-include="validateTemplate/email.html"> </div> </p> <p> <input type="submit" ng-disabled="mainForm.$invalid" />
Add a pair focused
of judgment in Ng-show, False when a prompt appears.
Now it's going to look like that.
The custom authentication method and the validity (validity), this also uses the instruction (Directive).
Verify that the email you have filled is already occupied, here is a simple simulation:
.directive(‘isAlreadyTaken‘, function() { return { require: ‘ngModel‘, link: function(scope, ele, attrs, ctrl) { ctrl.$parsers.push(function(val) { ctrl.$setValidity(‘emailAvailable‘, false); var emailTable = [ ‘[email protected]‘, ‘[email protected]‘, ‘[email protected]‘, ‘[email protected]‘, ‘[email protected]‘, ‘[email protected]‘]; for (var i=0;i<emailTable.length;i+=1) if(val==emailTable[i]) return; ctrl.$setValidity(‘emailAvailable‘, true); return val; }) } }})
Add is-already-taken
an attribute to the INPUT element and add a ng-message:
<p class="error" ng-message="emailAvailable">Already taken! try other email addresses!</p>
AngularJS-Form Validation