1. 程式人生 > >AngularJS form validation-表單驗證

AngularJS form validation-表單驗證

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