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。我们将讨论几个核心校验, 然后讲讲如何建一个检验。
1
2
3
4
|
<
form
name
=
"form"
novalidate>
<
label
name
=
"email"
>Your email</
label
>
<
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/"
/>
|
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请求当表单发生改变时。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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:
1
2
3
4
5
6
7
|
.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:
1
2
3
4
5
6
7
8
9
10
11
|
input.ng-invalid {
border
:
1px
solid
red
;
}
input.ng-valid{
border
:
1px
solid
green
;
}
|
未完待续