1. 程式人生 > >jQuery Validation中使用remote屬性進行非同步驗證

jQuery Validation中使用remote屬性進行非同步驗證

上篇說了jQuery validation外掛的使用,我們平時經常會有這種需求,就是在註冊的時候,我們需要非同步判斷該屬性是否已被佔用,比如郵箱是否已經被註冊? 
   jQuery validation中remote屬性便可以用來完成此功能: 

rules: {
    new_stuID: {
        required: true,
        digits: true,
        maxlength: 7,
        minlength: 7,
        remote:{
            url: 'check.php',
            type:'post',
            data:{
                new_stuID:function(){
                    return $("#new_stuID").val();
                }
            }
        }
    }
},
messages: {
    new_stuID: {
        required: '學號不能為空',
        digits: '學號必須是數字',
        maxlength: '學號必須為7位',
        minlength: '學號必須為7位',
        remote:'學號已被註冊'

    }
},

上面程式碼中rules屬性中使用了remote屬性進行驗證,並且在messages中規定了remote錯誤情況的錯誤資訊內容:

remote:{
   url: 'check.php', //填寫用於進行驗證的檔案位置
    type:'post', //傳輸方式
    data:{ //傳輸的資料
        new_stuID:function(){
            return $("#new_stuID").val();
        }
    }
}

我這裡只是簡單的進行了一下可行性驗證: 
check.php:

<?php
    $new_stuID = $_POST['new_stuID'];
    //我試著返回布林型的true和false但是均不成功,string型的就可以
    if($new_stuID == '1234567'){
        echo 'false';
    }
    else{
        echo 'true';
    }

?>

remote接受伺服器返回的資料進行資料合法性驗證,並進行相關正確和錯誤樣式的顯示,與其它屬性無異。

參考視訊:youtube, 需要*牆