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 輸入值不能大於 5min: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 自訂對應的錯誤提示文字,即可完成使用前端的即時表單檢查。