简体   繁体   English

输入如何仅接受 HEX 数字

[英]How input accepts only HEX numbers

I have an input field and I want to give this field a validation that accepts only hex numbers.我有一个输入字段,我想给这个字段一个只接受十六进制数字的验证。 So it should accept numbers from 0 to 9 and letters from A to F.所以它应该接受从 0 到 9 的数字和从 A 到 F 的字母。

Here is my input field:这是我的输入字段:

<input type="text" class="form-control" tabindex="9" maxlength="2">

How do you think I can achieve this?你觉得我怎么能做到这一点?

You can use regex expression for your problem i write a simple example for your input你可以使用正则表达式来解决你的问题我为你的输入写了一个简单的例子

<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>

another option is input type color like @groov_guy comment but you need to convert rgb values to hex like this post, so you need to set default value with hex format then when client change color you can get new hex code.另一个选项是输入类型颜色,如@groov_guy 评论,但您需要像这篇文章一样将 rgb 值转换为十六进制,因此您需要使用十六进制格式设置默认值,然后当客户端更改颜色时,您可以获得新的十六进制代码。 a basic codes as below基本代码如下

<input type="color" onchange="printColor(event)" value="#ff0000">

function printColor(ev) {
  const color = ev.target.value;
  console.log(color) // you can get hex value
  
}

sample link示例链接

https://css-tricks.com/color-inputs-a-deep-dive-into-cross-browser-differences/ https://css-tricks.com/color-inputs-a-deep-dive-into-cross-browser-differences/

You can add the pattern attribute to the input.您可以将模式属性添加到输入。 This won't prevent the user to write invalid information, but when submitting it will show a message.不会阻止用户写入无效信息,但在提交时会显示一条消息。 Also, you can add some styles to show that something is wrong before submit.另外,您可以在提交之前添加一些 styles 以表明有问题。

<input type="text" class="form-control" tabindex="9" maxlength="2" pattern="[0-9a-fA-F]+">

<style>
input:invalid {
  border: red solid 3px;
}
</style>

Try this尝试这个

<input type="text" class="form-control" onchange="validate($event)" tabindex="9" maxlength="2">

And in your .js在你的.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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM