前端框架若使用 Bootstrap,做輸入校驗首推 bootstrapValidator——它與 Bootstrap 的樣式體系天然協調,配置也直觀。
<link type="text/css" rel="stylesheet" href="${ctx}/components/validate/css/bootstrapValidator.css" />
<script type="text/javascript" src="${ctx}/components/validate/js/bootstrapValidator.js"></script>
<script type="text/javascript" src="${ctx}/components/validate/js/language/zh_CN.js"></script>
語言包要放在插件之後,它負責把預設提示文字替換成中文。
$('#yourFormId').bootstrapValidator({
message: '這裡寫默認提示信息',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
inputName: {
validators: {
notEmpty: {
message: '時間不能為空'
},
regexp: {
regexp: /^[0-9]+$/,
message: '時間由數字組成'
},
stringLength: {
min: 1,
max: 20,
message: '角色名長度必須在1到20之間'
}
}
}
}
});
message 是全域預設提示,validators 內部的 message 會覆蓋它,所以每條規則都能給專屬文案。feedbackIcons 直接複用 Bootstrap 的 glyphicon,校驗中、通過、失敗三種狀態會顯示不同圖示。regexp 適合格式類校驗(純數字、手機號、郵箱等);若規則複雜到正則難以表達,可以自訂 validator,自行實作 validate 方法並呼叫它。