Home > database >  How input accepts only HEX numbers
How input accepts only HEX numbers

Time:12-03

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.

Here is my input field:

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

How do you think I can achieve this?

CodePudding user response:

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

CodePudding user response:

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.

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

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

CodePudding user response:

Try this

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

And in your .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
}
  • Related