原生 JS 實現
<input type="text" id="test" value="333/2">
<script>
const input = document.getElementById('test');
function checkSlash() {
if (input.value.includes('/')) { // ES2016
ABC();
}
// 或舊版兼容
if (input.value.indexOf('/') >= 0) {
ABC();
}
}
function ABC() { console.log('包含斜杠'); }
// 綁定事件
input.addEventListener('blur', checkSlash);
input.addEventListener('input', checkSlash); // 實時檢測
</script>
正則驗證(更靈活)
const hasSlash = /\//.test(input.value); // 正則測試
// 或提取斜杠前後部分
const [left, right] = input.value.split('/');
表單驗證集成
<form onsubmit="return validate()">
<input id="path" required pattern="[^/]+(/[^/]+)*" title="路徑需含斜杠">
<button type="submit">提交</button>
</form>
<script>
function validate() {
const v = document.getElementById('path').value;
if (!v.includes('/')) {
alert('路徑必須包含斜杠');
return false;
}
return true;
}
</script>
性能提示
includes/indexOf O(n),極短字符串可忽略。
- 高頻實時檢測用
requestAnimationFrame 節流或 debounce。