我有一個輸入欄位,我想給這個欄位一個只接受十六進制數字的驗證。所以它應該接受從 0 到 9 的數字和從 A 到 F 的字母。
這是我的輸入欄位:
<input type="text" class="form-control" tabindex="9" maxlength="2">
你覺得我怎么能做到這一點?
uj5u.com熱心網友回復:
您可以使用正則運算式解決您的問題,我為您的輸入撰寫了一個簡單的示例
<input type="text" id="hex_code" name="hex_code" pattern="#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?" title="in valid hex code"><br><br>
另一個選項是輸入型別顏色,如@groov_guy 評論,但您需要像這篇文章一樣將 rgb 值轉換為十六進制,因此您需要使用十六進制格式設定默認值,然后當客戶端更改顏色時,您可以獲得新的十六進制代碼。基本代碼如下
<input type="color" onchange="printColor(event)" value="#ff0000">
function printColor(ev) {
const color = ev.target.value;
console.log(color) // you can get hex value
}
示例鏈接
https://css-tricks.com/color-inputs-a-deep-dive-into-cross-browser-differences/
uj5u.com熱心網友回復:
嘗試這個
<input type="text" class="form-control" onchange="validate($event)" tabindex="9" maxlength="2">
而在你 .js
validate(event) {
let regEx = "^[- ]?[0-9A-Fa-f] \.?[0-9A-Fa-f]*?$";
let isHex = regEx.match(event.target.value);
// Do things with isHex Boolean
}
編輯:如果你需要防止你可以做這樣的事情
var input = document.getElementById('input');
input.addEventListener('keyup', (event) => {
let regEx = /^[0-9a-fA-F] $/;
let isHex = regEx.test(event.target.value.toString());
if(!isHex) {
input.value = input.value.slice(0, -1);
}
})
<input type="text" class="form-control" id="input" tabindex="9" maxlength="2">
uj5u.com熱心網友回復:
您可以將模式屬性添加到輸入。這不會阻止用戶寫入無效資訊,但在提交時會顯示一條訊息。此外,您可以添加一些樣式以在提交之前顯示出問題。
<input type="text" class="form-control" tabindex="9" maxlength="2" pattern="[0-9a-fA-F] ">
<style>
input:invalid {
border: red solid 3px;
}
</style>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/377553.html
標籤:javascript html 验证 十六进制
