• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

144
Views
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.

Here is my input field:

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

How do you think I can achieve this?

almost 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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/

almost 3 years ago · Juan Pablo Isaza Report

0

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>
almost 3 years ago · Juan Pablo Isaza Report

0

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
}

EDIT: If you need to prevent you can do something like this

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

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error