DIV CSS 佈局教程網

jQuery validate 內建驗證規則使用教學(表單驗證)
編輯:JQuery特效代碼     

jQuery Validate 是一款強大的表單驗證插件,內建了大量常用的驗證規則。以下先列出常見的內建規則:

  • required:true 必填欄位
  • remote:"check.php" 使用 ajax 呼叫 check.php 驗證輸入值
  • email:true 必須為正確格式的電子郵件
  • url:true 必須為正確格式的網址
  • date:true 必須為正確格式的日期
  • dateISO:true 必須為正確格式的 ISO 日期(如 2009-06-23、1998/01/22),只驗證格式不驗證有效性
  • number:true 必須為合法數字(含負數、小數)
  • digits:true 必須為整數
  • creditcard 必須為合法的信用卡號
  • equalTo:"#field" 輸入值必須與 #field 相同
  • accept 輸入須具備合法副檔名的字串(用於上傳檔案)
  • maxlength:5 長度最多 5 的字元(中文字算一個)
  • minlength:10 長度最少 10 的字元
  • rangelength:[5,10] 長度介於 5 到 10 之間
  • range:[5,10] 輸入值介於 5 到 10 之間
  • max:5 輸入值不能大於 5
  • min:10 輸入值不能小於 10

完整範例

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>validate.js 內建驗證規則的使用</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
</head>
<body>
<form action="" method="get" id="tinyphp">
  <input type="text" value="" name="userName" />
  <input type="submit" value="提交" />
</form>
<script type="text/javascript">
$("#tinyphp").validate({
    // 添加驗證規則
    rules: {
        userName:{
            required: true,
            digits: true,
            rangelength: [5,10]
        }
    },
    // 重設提示訊息
    messages:{
        userName: {
            required: "請填寫用戶名",
            digits: "請輸入整數",
            rangelength: "用戶名必須在 5-10 個字元之間"
        }
    }
});
</script>
</body>
</html>

透過 rules 定義每個欄位的驗證規則,再以 messages 自訂對應的錯誤提示文字,即可完成使用前端的即時表單檢查。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved