acr acr - 3 months ago 24
HTML Question

How to restrict a textbox only to enter a hexadecimal value

I have a textbox in my HTML form, and I would like to restrict a user to enter a hexadecimal value in it between 0 and f. How can I do it?

My HTML textbox code:

<div class="input-resp-hpux-vbus"><span><input class="textbox" id="vbus-id" name="vbus-id" type="text" size="5" maxlength="3" value="<?php if(isset($_POST['vbus-id'])) { echo htmlentities ($_POST['vbus-id']); }?>" /></span></div>

Answer

You could use a regular expression and validate it before submit or after keypress:

Regular expression to validate hex string

var control = document.getElementById('vbus-id')';
var regExp = new RegExp(/^0x[0-9A-F]{1,4}$/i);
if (!regExp.test(control))
   alert('invalid');