Bootstrap 本身僅提供驗證狀態樣式(`.has-success`、`.has-error`、圖標),不包含驗證邏輯。生產環境推薦使用功能完善的 BootstrapValidator (現更名為 bootstrap-validator 或 FormValidation)。
<link href="css/bootstrapValidator.min.css" rel="stylesheet">
<script src="js/bootstrapValidator.min.js"></script>
<form id="registerForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-sm-3 control-label">郵箱</label>
<div class="col-sm-5">
<input type="email" class="form-control" name="email" />
</div>
</div>
<!-- 更多字段 -->
</form>
$('#registerForm').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
email: {
validators: {
notEmpty: { message: '郵箱不能為空' },
emailAddress: { message: '郵箱格式不正確' }
}
},
phone: {
validators: {
notEmpty: { message: '手機號不能為空' },
regexp: { regexp: /^1[3-9]\d{9}$/, message: '手機號格式錯誤' }
}
},
username: {
validators: {
notEmpty: { message: '用戶名不能為空' },
stringLength: { min: 3, max: 20, message: '長度 3-20' },
regexp: { regexp: /^[a-zA-Z0-9_]+$/, message: '只能字母數字下劃線' },
remote: { url: '/checkUser', message: '用戶名已存在' } // 異步驗證
}
}
}
});
| 驗證器 | 用途 | 示例 |
|---|---|---|
| notEmpty | 非空 | {} |
| stringLength | 長度範圍 | {min: 6, max: 30} |
| regexp | 正則 | {regexp: /^[a-z]+$/} |
| emailAddress | 郵箱格式 | {} |
| identical | 與某字段相同 | {field: 'password'} |
| remote | 異步服務端驗證 | {url: '/api/check', type: 'POST'} |
| callback | 自定義函數 | {callback: function(v, $f) { return v > 10; }} |
官方示例與文檔:BootstrapValidator 中文教程 | FormValidation Bootstrap 範例