$(function () { $("#form-test").bootstrapValidator({ live: 'disabled',//驗證時機,enabled是內容有變化就驗證(默認),disabled和submitted是提交再驗證 excluded: [':disabled', ':hidden', ':not(:visible)'],//排除無需驗證的控件,比如被禁用的或者被隱藏的 submitButtons: '#btn-test',//指定提交按鈕,如果驗證失敗則變成disabled,但我沒試成功,反而加了這句話非submit按鈕也會提交到action指定頁面 message: '通用的驗證失敗消息',//好像從來沒出現過 feedbackIcons: {//根據驗證結果顯示的各種圖標 valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { text: { validators: { notEmpty: {//檢測非空,radio也可用 message: '文本框必須輸入' }, stringLength: {//檢測長度 min: 6, max: 30, message: '長度必須在6-30之間' }, regexp: {//正則驗證 regexp: /^[a-zA-Z0-9_\.]+$/, message: '所輸入的字符不符要求' }, remote: {//將內容發送至指定頁面驗證,返回驗證結果,比如查詢用戶名是否存在 url: '指定頁面', message: 'The username is not available' }, different: {//與指定文本框比較內容相同 field: '指定文本框name', message: '不能與指定文本框內容相同' }, emailAddress: {//驗證email地址 message: '不是正確的email地址' }, identical: {//與指定控件內容比較是否相同,比如兩次密碼不一致 field: 'confirmPassword',//指定控件name message: '輸入的內容不一致' }, date: {//驗證指定的日期格式 format: 'YYYY/MM/DD', message: '日期格式不正確' }, choice: {//check控件選擇的數量 min: 2, max: 4, message: '必須選擇2-4個選項' } } } } }); $("#btn-test").click(function () {//非submit按鈕點擊后進行驗證,如果是submit則無需此句直接驗證 $("#form-test").bootstrapValidator('validate');//提交驗證 if ($("#form-test").data('bootstrapValidator').isValid()) {//獲取驗證結果,如果成功,執行下面代碼 alert("yes");//驗證成功后的操作,如ajax } }); });