Xử lý giá trị Form – AngularJS Form Validation, AngularJS năm 2009

Xử lý giá trị Form – AngularJS Form Validation, AngularJS năm 2009

AngularJS Form Validation là một phần khá hay của AngularJS, nó cung cấp cho chúng ta một số phương thức cơ bản để validate form mạnh mẽ như required, pattern, min, max, minlength, maxlength … Ngoài ra AngularJS còn cho phép chúng ta tạo ra những validation của chính mình.

Hôm nay, chúng ta sẽ tìm hiểu về những cách mà AngularJS giúp chúng ta validate form. Để bắt đầu, bạn hãy xem demo bên dưới, chúng ta sẽ tạo 1 trang đăng ký giống như Demo này.

Chúng ta khởi tạo các file sau:

Validation trong AngularJS

Cấu trúc file trong ứng dụng demo

Thư viện yêu cầu:

– AngularJS

– JQuery

Trong demo này mình có sử dụng Bootstrap và Fontawesome để tạo giao diện cho ứng dụng được đẹp hơn, bạn có thể bỏ qua 2 thư viện này, chúng không ảnh hưởng tới chức năng của ứng dụng.

<link rel="stylesheet"

  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

<link rel="stylesheet"

  href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css" />

<script src="//code.jquery.com/jquery-1.11.0.min.js">

</script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">

</script>

Đầu tiên là giao diện của trang đăng ký:

<div id="main" ng-app="demoApp" ng-controller="RegisterCtrl">

<form id="register-form" class="form-horizontal" name="form" >

<div class="form-group">

    <label for="email" class="col-xs-3 control-label required">Email</label>

<div class="col-xs-9">

      <input name="email" type="email" class="form-control"

        placeholder="Email" ng-model="email" autocomplete="off" >

    </div>
 </div>

<div class="form-group">

    <label for="password" class="col-xs-3 control-label required">Mật khẩu

</label>

<div class="col-xs-9">

      <input name="password" ng-model="password" type="password"

         placeholder="Mật khẩu">

    </div>

 </div>

<div class="form-group">

    <label for="username" class="col-xs-3 control-label required">Tên đăng nhập

    </label>

<div class="col-xs-9">

      <input name="username" type="text" class="form-control"

       placeholder="Tên đăng nhập" ng-model="username">

    </div>

 </div>

<div class="form-group">

    <label for="birthday" class="col-xs-3 control-label">Ngày sinh

    </label>

<div class="col-xs-9">

       <input name="birthday" type="text" ng-model="birthday"

          class="form-control" placeholder="dd-mm-yyyy" >
    </div>

 </div>

<div class="form-group">

<div class="col-sm-offset-3 col-xs-9">

      <button type="submit" class="btn btn-primary" >

Đăng ký <i class="fa fa-sign-in"></i></button>
    </div>

 </div>

 </form>

</div>

Trong đoạn code giao diện này, các bạn cần lưu ý. ng-app=”demoApp” tên module mà chúng ta đặt để AngularJS quản lý.

RegisterCtrl là controller sẽ quản lý ứng dụng này.

Tiếp theo, ta sẽ tắt chế độ validate mặc định của trình duyệt bằng cách thêm thuộc tính novalidate vào thẻ form để tránh bị lặp thông báo mặc định của trình duyệt.

<form class="form-horizontal" name="form" ng-submit="register()" novalidate>
 

ng-submit="register()" là tên hàm thực thi khi form submit (hàm này chúng ta sẽ viết sau trong controller RegisterCtrl)

<input name="email" type="email" class="form-control" placeholder="Email"  ng-model="email" autocomplete="off" >
 

Tiếp theo chúng ta thiết lập một số thuộc tính cơ bản cho các input như name (bắt buộc để xác định trường validate), ng-model cho các input, đây là 2 thuộc tính quan trọng cần có. Các bạn làm tương tự với các input khác.

Bước tiếp theo là thiết lập các ràng buộc dữ liệu cho các trường như email, mật khẩu, họ tên và ngày sinh thì bắt buộc phải nhập. Mật khẩu phải có độ dài bằng 6 trở lên và ngắn hơn 30 kí tự, họ tên phải dài hơn 6 kí tự và nhỏ hơn 50 kí tự, ngày sinh phải là ngày hợp lệ. Ta làm như sau:

Email :

<input type="email" name="email" class="form-control" placeholder="Email"   ng-model="email" autocomplete="off" required >
 

Mật khẩu:

<input name="password" ng-model="password" type="password" class="form-control"  placeholder="Mật khẩu" ng-minlength="6" ng-maxlength="30" required>
 

Họ tên:

<input name="username" type="text" class="form-control"  placeholder="Tên đăng nhập"  ng-model="username"  ng-minlength="6"  ng-maxlength="50" ng-pattern="/^[a-zA-Z]+$/" required>
 

Trường họ tên mình có sử dụng thêm pattern sử dụng regular expression (biểu thức chính quy) để check điều kiện dữ liệu nhập vào phải là chữ cái.

Tương tự với ngày sinh

<input name="birthday" type="text" ng-model="birthday"  class="form-control" placeholder="dd-mm-yyyy" ng-pattern="/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-((19[0-9]{2})|(20[0-1]{1}[0-4]{1}))$/">

Tiếp theo là xử lý cho button đăng ký

<button type="submit" class="btn btn-primary"  ng-disabled="!form.$dirty || (form.$dirty && form.$invalid)">
 
Đăng ký <i class="fa fa-sign-in"></i></button>
 

Trong đoạn code trên các bạn lưu ý thuộc tính ng-disabled, thuộc tính này nếu bằng true thì button sẽ bị disable và chúng ta không thể click để submit form được.

ng-disabled="!form.$dirty || (form.$dirty && form.$invalid)"
 

Đoạn code này có nghĩa là form chưa được nhập liệu hoặc là đã được nhập liệu nhưng dữ liệu không hợp lệ thì nút sẽ bị vô hiệu hóa.

OK, chúng ta đã thiết lập xong các thuộc tính cần thiết cho form cần validate. Và giờ chúng ta sẽ hiển thị câu thông báo lỗi tương ứng với từng trường hợp.

Chúng ta sẽ sử dụng ng-show để ẩn và hiện câu thông báo. Ví dụ cho trường email, ta sẽ thêm đoạn code sau dưới thẻ <input type=”email” />

<i class="fa fa-check text-success" ng-show="form.email.$dirty && form.email.$valid">

</i>


<!--Dấu check thể hiện việc nhập dữ liệu được nhập là hợp lệ-->


<div ng-show="form.email.$dirty && form.email.$invalid" class="text-danger">

<i class="fa fa-times text-danger"></i>


<!--Nếu dữ liệu không hợp lệ-->

<span ng-show="form.email.$error.required">Bạn chưa nhập địa chỉ email</span>


<!--Custom thông báo email không được rỗng-->

<span ng-show="form.email.$error.email">Không đúng định dạng email</span>


<!--Thông báo email sai định dạng-->
 

Các bạn làm tương tự với các input khác:

<div class="form-group">

<label for="password" class="col-xs-3 control-label required">Mật khẩu

</label>

<div class="col-xs-9">

<input name="password" ng-model="password" type="password"class="form-control"

 placeholder="Mật khẩu" ng-minlength="6" ng-maxlength="30" required>

<i class="fa fa-check text-success" ng-show="form.password.$dirty && form.password.$valid">

</i>

<div ng-show="form.password.$dirty && form.password.$invalid" class="text-danger">

<i class="fa fa-times text-danger"></i>

<span ng-show="form.password.$error.required">

  Mật khẩu không được bỏ trống

</span>

<span ng-show="form.password.$error.minlength">

  Mật khẩu phải dài hơn 6 kí tự

</span>

<span ng-show="form.password.$error.maxlength">

  Mật khẩu phải ngắn hơn 30 kí tự

</span>

</div>

</div>

</div>

<div class="form-group">

 <label for="username" class="col-xs-3 control-label required">

  Tên đăng nhập

 </label>

<div class="col-xs-9">

 <input name="username" type="text" class="form-control"

 placeholder="Tên đăng nhập" ng-model="username" ng-minlength="6"

 ng-maxlength="50" ng-pattern="/^[a-zA-Z]+$/" required>

 <i class="fa fa-check text-success"

 ng-show="form.username.$dirty && form.username.$valid">

</i>

<div ng-show="form.username.$dirty && form.username.$invalid" class="text-danger">

<i class="fa fa-times text-danger"></i>

<span ng-show="form.username.$error.required"> Họ tên không được bỏ trống </span>

<span ng-show="form.username.$error.minlength"> Họ tên phải dài hơn 6 kí tự </span>

<span ng-show="form.username.$error.maxlength"> Họ tên phải ngắn hơn 50 kí tự </span>

<span ng-show="form.username.$error.pattern"> Họ tên chỉ bao gồm các kí tự chữ cái </span>

</div>

</div>

</div>

<div class="form-group">

<label for="birthday" class="col-xs-3 control-label"> Ngày sinh </label>

<div class="col-xs-9">

<input name="birthday" type="text" ng-model="birthday" class="form-control"

placeholder="dd-mm-yyyy" ng-pattern="/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-((19[0-9]{2})|(20[0-1]{1}[0-4]{1}))$/"> 

<i class="fa fa-check text-success" ng-show="form.birthday.$dirty && form.birthday.$valid"> </i>

<div ng-show="form.birthday.$dirty && form.birthday.$invalid" class="text-danger">

<i class="fa fa-times text-danger"></i> Nhập ngày sinh theo đúng định dạng dd-mm-yyyy {{birthday}}

</div>

</div>

</div>
 

Cuối cùng là tạo function xử lý khi submit form, ở đây đơn giản mình chỉ cho hiện ra câu thông báo thành công khi nhấn submit.

HTML

<div ng-show="success" class="text-success text-center">

 Đăng ký thành viên thành công !

</div>
 

Javascript

var demoApp = angular.module('demoApp',[])

 .controller( "RegisterCtrl", ['$scope', function($scope) {

 $scope.success = false;

 $scope.register = function() {

 $scope.success=true;

 }

 }]);
 

Khi mới load trang thì biến success sẽ có giá trị là false vì vậy câu thông báo không được hiển thị, sau khi nhấn submit thì giá trị success được set lại là true và câu thông báo được hiển thị.

Vậy là đã xong, bạn hãy chạy thử ứng dụng và tận  hưởng thành quả.

Nhập hợp lệ:

AngularJS Form Validation

Kết quả khi nhập dữ liệu hợp lệ

Mở rộng: Bạn có thể CSS thêm cho các thông báo lỗi.

input.ng-dirty{

   border-bottom: 1px solid yellow;

}

input.ng-invalid.ng-dirty{

   border-bottom: 1px solid red;

}

input.ng-valid.ng-dirty{

   border-bottom: 1px solid green;

}

input.ng-invalid-minlength.ng-dirty{

   border-bottom: 1px solid blue;

}

input.ng-invalid-maxlength.ng-dirty{

   border-bottom: 1px solid blue;

}

Do khả năng trình bày của mình chưa tốt lắm nên có thể các bạn nghe qua khó hiểu, các bạn có thể xem full source Tại đây để hiểu rõ hơn.

Tags: 
Bạn thấy bài viết này như thế nào?: 
No votes yet
Ảnh của Tommy Tran

Tommy owner Express Magazine

Drupal Developer having 9+ year experience, implementation and having strong knowledge of technical specifications, workflow development. Ability to perform effectively and efficiently in team and individually. Always enthusiastic and interseted to study new technologies

  • Skype ID: tthanhthuy

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Tạo Redirecting Links từ 1 Page cũ sang 1 Page mới

Tạo Redirecting Links từ 1 Page cũ sang 1 Page mới

Websites often link to pages on other websites – this is a great way to refer to relevant information from your site. However, problems arise when a page that people are linking to moves to a new URL in your site or elsewhere

Google Mua Thêm 217 Bằng Sáng Chế Từ IBM

Google Mua Thêm 217 Bằng Sáng Chế Từ IBM

Theo thông tin có được từ blog SEO by the Sea mới đây thì Google vừa hoàn thành thương vụ mua lại 217 bằng sáng chế từ IBM với....

Phiên bản Android 2.3 Gingerbread  nổi tiếng nhất thế giới

Phiên bản Android 2.3 Gingerbread nổi tiếng nhất thế giới

Mặc dù đã ra mắt từ cách đây 2 năm, tuy nhiên phiên bản 2.3 Gingerbread mới là phiên bản Android phổ biến nhất trên thế giới hiện nay, chứ không phải là các phiên bản mới như Android 4.0 Ice Cream Sandwich hay 4.1 Jelly Bean.

Công ty diệt chuột T&C

 

Diet con trung