When taking input from our users, it's important to show visual feedback on their input.
In the context of human relationships, form validation is just as much about giving feedback as well as getting the "right" input.
當從使用者那裡得到輸入的時候,給使用者一個視覺上的反饋很重要。表單驗證的目的是為了給予反饋,同樣也是為了得到正確的輸入。
Not only does it provide positive feedback for our user, it will also semi-protect our web app from bad or invalid input.
We can only protect our back end as much as is possible with our web front end.
它不僅為我們的使用者提供了積極的反饋,也為錯誤或非法的輸入給我們的應用提供了一些保護。我們只能儘可能的在前端添加措施來保護後端。
Out of the box, AngularJS support form validation with a mix of the HTML5 form validation inputs
as well as with its own validation directives.
創造性地,在表單校正上,AngularJS既支援HTML5地混合表單校正,當然還有內建的用來校正的directives.
There are many form validation directives available in AngularJS.
We'll talk about a few of the core validations, then we'll get into how to build your own validations.
AngularJS中有許多用來校正的directives。我們將討論幾個核心校正, 然後講講如何建一個檢驗。
| 1234 |
<form name="form" novalidate> <label name="email">Your emaillabel> <input type="email" name="email" ng-model="email" placeholder="Email Address" />form> |
AngularJS makes it pretty easy for us to handle client-side form validations without adding a lot of extra effort.
Although we can't depend on client-side validations to keep our web application secure,
they do provide instant feedback of the state of the form.
AngularJS 使你不用做很多額外得工作,就能夠不費吹灰之力地處理用戶端的表單驗證。儘管們不能依賴用戶端的驗證來保持應用的安全性,但它們可以給你即時的表單狀態的反饋。
To use form validations,
we first must ensure that the form has a name associated with it,
like in the above example.
為了使用表單驗證,我們首先要保證表單要有一個名字,就像上面的例子。
All input fields can validate against some basic validations,
like minimum length, maximum length, etc.
These are available on the new HTML5 attributes of a form.
所有的輸入框可以做一些基本驗證,如最小長度,最大長度等。這些都是新HTML5中表單的屬性。
It is usually a great idea to use the novalidate flag on the form element,
as it prevents the browser from natively validating the form.
通常來說,給表單加上novalidate屬性是個好注意。這樣做可以阻止表單自身的驗證動作。
Let's look at all the validation options we have that we can place on an input field:
讓我們來看看可以放到input上的驗證項:
Required
To validate that a form input has been filled out,
we simply add the HTML5 tag, required, to the input field:
| 1 |
<input type="text" required /> |
Minimum Length
To validate that a form input input is at least a certain {number} of charaters,
we add the AngularJS directive ng-minlength="{number}" to the input field:
| 1 |
<input type="text" ng-minlength=5 /> |
Maximum Length
To validate that a form input is equal to or less than a number of characters,
we can add the AngularJS directive ng-maxlength="{number}":
| 1 |
<input type="text" ng-maxlength=20 /> |
Matches a Pattern
To ensure that an input matches a regex, we can use ng-pattern="/PATTERN/";
| 1 |
<input type="text" ng-pattern="/a-zA-Z/" /> |
Email
To validate an email address in an input field, we simply set the input type to email, like so:
| 1 |
<input type="email" name="email" ng-model="user.email" /> |
URL
To validate that an input represents a URL, set the input type to url:
| 1 |
<input type="url" name="homepage" ng-model="user.facebook_url" /> |
Custom Validations
AngularJS makes it very easy to add our own validations, as well, by using directives.
For instance, let's say that we want to validate that our username is available in the database.
To do so, we'll implement a directive that fires an Ajax request whenever the form changes.
同樣地,AngularJS很容易建立我們自己的directives。
舉個例子,比方說我們想要驗證使用者名稱是否可用。為了達到目的,我們執行一個directive來觸發一個ajax請求當表單發生改變時。
| 12345678910111213141516171819 |
angular.module('validationExample', []).directive('ensureUnique', function($http){ return { require: 'ngModel', link: function(scope, ele, attrs, c){ scope.$watch(attrs.ngModel, function(){ $http({ method: 'POST', url: '/api/check/" + attrs.ensureUnique, data: {'field': attrs.ensureUnique} }).success(function(data, status, headers, cfg){ c.$setValidity('unique', data.isUnique); }).error(function(data, status, headers, cfg){ c.$setValidity('unique', false); }); }); } } }); |
Control Variables in Forms
AngularJS makes properties available on the containing $scope object available to us as a result of
setting a form inside of the DOM.
These properties enable us to react to the form in real time (just like everything else in AngularJS).
The properties that are available to us are:
(Note that these properties are made availabel to us in the format:)
| 1 |
formName.inputFieldName.property |
Unmodified Form
This property is a boolean that tells us whether the user has modified the form.
It is true if the user hasn't touched the form, and false if they have:
| 1 |
formName.inputFieldName.$pristine |
Modified Form
This property is a boolean that tells us if and only if the user has actually modified the form.
It is set regardless of validations on the form:
| 1 |
formName.inputFieldName.$dirty |
Vaild Form
This property is a boolean that tells us whether or not the form is valid.
If the form is currently valid, then the following will be true:
| 1 |
formName.inputFieldName.$valid |
Invalid Form
The property is a boolean that tells us whether or not the form is invalid.
If the form is currently invalid, then the following will be true:
| 1 |
formName.inputFieldName.$invalid |
The last two properties are particularly useful for showing or hiding DOM elements.
They are also very useful when setting a class on a particular form.
Errors
This property is another useful one that AngularJS makes available to us: the $error object.
This object contains all of the validations on a paticular form and a record of whether they are valid or invalid.
To get access to this property, use the following syntax:
| 1 |
formName.inputfieldName.$error |
If a validation fails, then this property will be true; if it is false, then the value has passed the input field.
A Little Style Never Hurts
When AngularJS is handling a form,
it adds specific classes to the form based upon the current state of the form(i.e. if it's currently valid, unchanged, etc).
These classes are named similarly to the properties that we can check, as well.
These classes are:
| 1234567 |
.ng-pristine {} .ng-dirty {} .ng-valid {} .ng-invalid {} |
They correspond to their counterpart on the particular input field.
When a field is invalid, the .ng-invalid class will be applied to the field. This particular site sets the CSS class as:
| 1234567891011 |
input.ng-invalid { border: 1px solid red; } input.ng-valid{ border: 1px solid green; } |
未完待續