There is a textbox in the form, in which only specific number inputs are allowed. i.e
0.5, 1, 1.5, 2, 2.5, 3........ and so on
How can i mask this textbox for these inputs? Or what regex should i use?
If you only want to validate on submit, you can simply use parseFloat, Math.floor and toString:
function isValidValue(text) {
return text == (Math.floor(parseFloat(text) * 2) / 2).toString();
}
Or you can perform a regex check with string replace, .replace(/[^0-9\.]/g, ""). That only allows numbers and periods/decimal points. Unfortunately, it does not prevent multiple decimal points.
If you want to restrict actual keystrokes, you need something more. Attach the following function to the keyup event for your textbox. Remember to use return isValidKey(this, event) instead of simply isValidKey(this, event):
function isValidKey(me, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var currValue = me.value;
// disallow decimal point if it is not the first one
if ((charCode == 46 || charCode == 110 || charCode == 190) && currValue.indexOf(".") != -1)
return false;
// disallow non numeric characters
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Update: It is now slightly more strict, but still not foolproof. You can still have a number with a leading 0 or start with a decimal point if the user uses backspace or delete to remove the original starting numbers.
You can look here:
http://digitalbush.com/projects/masked-input-plugin/
but it doesn't fully solve your problem, just allows a mask, not predefined values. You can modify the plugin code though for your needs.
For this control I would put the up and down arrow that increment/decrement and I would allow the free text that will validate on losing focus and round up the value to the nearest half. I think that would be most convenient. Masks could be annoying when they don't allow you to type text in.