JQUERY TUTORIALS
CÁC CHỦ ĐỀ
BÀI MỚI NHẤT
MỚI CẬP NHẬT

Bài 01: Hướng dẫn sử dụng jQuery validation - basic

Khi sử dụng form để lấy thông tin từ người dùng thì bước quan trọng nhất chính là validate kiểm tra định dạng dữ liệu trước khi xử lý. Điều này nhằm giúp hệ thống chạy đúng với ràng buộc dữ liệu, đồng thời cũng là giúp cho hệ thống được bảo mật hơn. Tuy nhiên công đoạn validate rất là dài dòng, gây mất thời gian cho coder. Nắm được nhu cầu này nên nhiều tác giả đã tạo ra một bộ thư viện jQuery dùng để kiểm tra dữ liệu. Ta hay gọi là jQuery Validation.

test php

banquyen png
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Để làm được điều này trước tiên bạn cần lên trang chủ jQuery validation để download nhé. Sau khi download về ta sẽ có 2 file đó là:

  • jquery-validate.js
  • jquery-validate.min.js

Hai file này đều có công dụng như nhau, chỉ có một sự khác biệt là file jquery-validate.min.js có dung lượng nhẹ hơn nên ta thường sử dụng nó để up lên host.

Và vì jquery validate được viết từ thư viện jQuery nên bạn cũng cần phải import file jquery vào nhé.

Bài viết này được đăng tại [free tuts .net]

1. Sử dụng jquery validate mức căn bản

Bạn tạo file basic.php với nội dung như sau:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>jQuery Validation</title>
        <style>
            .success{border: solid 1px blue;}
            .error {border:solid 1px red;}
        </style>
        <script src="./jquery-1.9.0.min.js"></script>
        <script src="./jquery-validate.js"></script>
    </head>
    <body>
        <header class="container">
            <h1>BASIC DEMO</h1>
        </header>
        <div class="container">
            <form id="form">
                <div>
                    <input type="text" name="name" id="name" form="form" data-required />
                    <label for="name">Name</label>
                </div>
                <div>
                    <input type="text" name="nickname" id="nickname" data-required />
                    <label for="nickname">Nickname</label>
                </div>
                <div>
                    <input type="text" name="site" id="site" />
                    <label for="site">Site</label>
                </div>
                <div>
                    <input type="text" name="age" id="age" data-required data-pattern="^[0-9]+$" />
                    <label for="age">Age</label>
                </div>
                <div>
                    <button type="submit">Send</button>
                    <button type="reset">Reset</button>
                </div>
            </form>
        </div>
        
    </body>
</html>
Chạy lên ta sẽ có giao diện như sau:

huong-dan-su-dung-jquery-validation

Trong file này tôi có viết style cho hai class là error success, tôi có import hai thư viện jquery và jquery-validate vào. Bây giờ tôi sẽ đưa ra những rule validate như sau:

  • Name: required
  • Nickname: required
  • Site: Không validate
  • Age: Required và là Number

Như vậy, các bạn để ý trong form các thẻ input tôi có truyền vào một số thuộc tính riêng của thư viên jquery validate như hình dưới đây:

huong-dan-su-dung-jquery-validation

Từ hình ta rút ra kết luận như sau:

  • Tất cả các rule require tôi đã dùng thộc tính data-required để định nghĩa. 
  • Còn với kiểu số thì tôi có định nghĩa thêm một partern data-pattern="^[0-9]+$".  Đây là kiến thức Regular Expression nên nếu bạn không rành có thể đọc qua serie đó.

Bước tiếp ta sẽ viết đoạn code jquery validate để kiểm tra các định dạng trên. Nội dung như sau:

<script>
    $(document).ready(function(){
        // Khai báo validate cho thẻ form
        $('form').validate(
        {
            // Thiết lập validate cho sự kiện keyup
            onKeyup: true, 

            // Function sẽ gọi khi validate thành cong
            eachValidField: function() {
                // Validate thành công thì xóa class error và add class success
                $(this).removeClass('error').addClass('success');
            },

            // Function sẽ gọi khi validate thất bại
            eachInvalidField: function() {
                // Validate thất bại thì xóa class success và add class error
                $(this).removeClass('success').addClass('error');
            }
        });
    });
</script>
Trong đoạn code này tôi có sử dụng một số hàm jquery như addClass() và removeClass() trong jquery để thêm hoặc xóa các class error và success nhằm mục đích hiển thị border màu đỏ cho error và màu xanh cho succes. Như vậy ta có tổng code cho file này như sau:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>jQuery Validation</title>
        <style>
            .success{border: solid 1px blue;}
            .error {border:solid 1px red;}
        </style>
        <script src="./jquery-1.9.0.min.js"></script>
        <script src="./jquery-validate.js"></script>
        <script>
            $(document).ready(function(){
                // Khai báo validate cho thẻ form
                $('form').validate(
                {
                    // Thiết lập validate cho sự kiện keyup
                    onKeyup: true, 
                    
                    // Function sẽ gọi khi validate thành cong
                    eachValidField: function() {
                        // Validate thành công thì xóa class error và add class success
                        $(this).removeClass('error').addClass('success');
                    },
                            
                    // Function sẽ gọi khi validate thất bại
                    eachInvalidField: function() {
                        // Validate thất bại thì xóa class success và add class error
                        $(this).removeClass('success').addClass('error');
                    }
                });
            });
        </script>
    </head>
    <body>
        <header class="container">
            <h1>BASIC DEMO</h1>
        </header>
        <div class="container">
            <form id="form">
                <div>
                    <input type="text" name="name" id="name" form="form" data-required />
                    <label for="name">Name</label>
                </div>
                <div>
                    <input type="text" name="nickname" id="nickname" data-required />
                    <label for="nickname">Nickname</label>
                </div>
                <div>
                    <input type="text" name="site" id="site" />
                    <label for="site">Site</label>
                </div>
                <div>
                    <input type="text" name="age" id="age" data-required data-pattern="^[0-9]+$" />
                    <label for="age">Age</label>
                </div>
                <div>
                    <button type="submit">Send</button>
                    <button type="reset">Reset</button>
                </div>
            </form>
        </div>        
    </body>
</html>

Xem demo

2 Lời kết

Vì bài hơi dài nên có lẽ tôi sẽ chia thành nhiều phần khác nhau. Trong bài này ta chỉ tìm hiểu cách sử dụng đơn giản của bộ thư viện jquery validate, trong bài tiếp theo ta sẽ tìm hiểu nâng cao hơn, tôi không muốn đi quá nhanh để những bạn mới tìm hiểu jquery có thể tham khảo được.

Cùng chuyên mục:

Cách dùng .bind() trong JQuery

Cách dùng .bind() trong JQuery

Cách dùng .delegate() trong JQuery

Cách dùng .delegate() trong JQuery

slideUp() và slideDown() trong jQuery

slideUp() và slideDown() trong jQuery

Nếu nói đến hiệu ứng slide thì ta phải tìm đến những ...

fadeIn() và fadeOut() trong jQuery

fadeIn() và fadeOut() trong jQuery

Không giống như show và hide, fadeIn và fadeOut sẽ hiển thị hoặc mờ ...

Show() và Hide() trong jQuery

Show() và Hide() trong jQuery

Hàm hide chỉ đơn giản là thiết lập thuộc tính ...

jQuery selector là gì? Trọn bộ selector trong jQuery đầy đủ nhất

jQuery selector là gì? Trọn bộ selector trong jQuery đầy đủ nhất

Trong bài này chúng ta sẽ tìm hiểu về Selector trong jQuery, đây là bài…

jQuery là gì? Cách viết jQuery cho người mới bắt đầu

jQuery là gì? Cách viết jQuery cho người mới bắt đầu

Trong công nghệ web 2.0 thì Javascript là một

Cách ẩn hiện nội dung khi click vào button trong jQuery

Cách ẩn hiện nội dung khi click vào button trong jQuery

Cách dùng All Selector (“*”) trong jQuery

Cách dùng All Selector (“*”) trong jQuery

Cách dùng All Selector (“*”) trong jQuery

Cách dùng :animated Selector trong jQuery

Cách dùng :animated Selector trong jQuery

Cách dùng :animated Selector trong jQuery

Cách dùng Attribute Contains Prefix Selector [name|=”value”] trong jQuery

Cách dùng Attribute Contains Prefix Selector [name|=”value”] trong jQuery

Cách dùng Attribute Contains Prefix Selector [name|=”value”] trong jQuery

Cách dùng Attribute Contains Selector [name*=”value”] trong jQuery

Cách dùng Attribute Contains Selector [name*=”value”] trong jQuery

Cách dùng Attribute Contains Selector [name*=”value”] trong jQuery

Cách dùng Attribute Contains Word Selector [name~=”value”] trong jQuery

Cách dùng Attribute Contains Word Selector [name~=”value”] trong jQuery

Cách dùng Attribute Contains Word Selector [name~=”value”] trong jQuery

Cách dùng Attribute Ends With Selector [name$=”value”] trong jQuery

Cách dùng Attribute Ends With Selector [name$=”value”] trong jQuery

Cách dùng Attribute Ends With Selector [name$=”value”] trong jQuery

Cách dùng Attribute Equals Selector [name=”value”] trong jQuery

Cách dùng Attribute Equals Selector [name=”value”] trong jQuery

Cách dùng Attribute Equals Selector [name=”value”] trong jQuery

Cách dùng Attribute Not Equal Selector [name!=”value”] trong jQuery

Cách dùng Attribute Not Equal Selector [name!=”value”] trong jQuery

Cách dùng Attribute Not Equal Selector [name!=”value”] trong jQuery

Cách dùng Attribute Starts With Selector [name^=”value”] trong jQuery

Cách dùng Attribute Starts With Selector [name^=”value”] trong jQuery

Cách dùng Attribute Starts With Selector [name^=”value”] trong jQuery

Cách dùng :button Selector trong jQuery

Cách dùng :button Selector trong jQuery

Cách dùng :button Selector trong jQuery

Cách dùng :checkbox Selector trong jQuery

Cách dùng :checkbox Selector trong jQuery

Cách dùng :checkbox Selector trong jQuery

Cách dùng :checked Selector trong jQuery

Cách dùng :checked Selector trong jQuery

Cách dùng :checked Selector trong jQuery

Top