I have a requirement wherein i need to allow plus/minus sign in the beginning followed by a decimal number which allows only one dot in it in a text field input in html.
Bascially the text field should allow normal integer numbers and decimal numbers and also negative integer and negative decimal numbers. The plus and minus sign should be allowed only in the beginning (first character) and it's optional. Also should allow any number of decimal places (ex: -12.12345 etc) but only one decimal (dot) in the entry.
Digits allowed are: 1, + 1, -1, .1, +1.1, -1.1, -.12, +.12, 123.4456, -123.345, +123.345 etc
Any help is highly appreciated.
I'm using below regex for the above requirement.
var integerOnly = /[\+\-0-9\.]/g;
and below script (which i obtained from some other thread with slight modification) to validate it .
function restrictInput(myfield, e, restrictionType, checkdot){
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert("1 " + character);
// if user pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
//alert("2");
// ignore if the user presses other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
alert("3");
if (character.match(restrictionType)) {
alert("4");
if(checkdot == "checkdot" & '-' != character & '+' != character){
alert("5");
return !isNaN((myfield.value.toString()==''? '0':myfield.value.toString())+character );
} else {
return true;
}
} else {
return false;
}
}
}
Here is how the script is called.
<input type="text" id="db" width="3" value="" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');"/>
It works fine except for few cases like:
- It allows +/- any place any number of times. My requirement is to allow only at the beginning.
I tried to modify the regex as below.
var integerOnly = /[\+\-]?[0-9\.]/g;
In that case, it doesn't match the expression. It doesn't reach alert 4.
One thing is it allows only one decimal places and not more than one.
Can someone help me to modify my regular expression so as to allow only +/- in the beginning and only once.
Thank you.