473,387 Members | 1,440 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Limiting characters in a text box

Hi all

I have a input filed of type "textbox" into which I am expecting to get
currency values (ie. 199.99). Is there a way that I can restrict the
user to only entering 2 values after the decimal point?

I can restrict the maxlength to 5, but that wouldn't stop the user from
type in 1.987.

tia
rogue chameleon

Jul 23 '05 #1
10 2781


Rogue Chameleon wrote:

I have a input filed of type "textbox" into which I am expecting to get
currency values (ie. 199.99). Is there a way that I can restrict the
user to only entering 2 values after the decimal point?

I can restrict the maxlength to 5, but that wouldn't stop the user from
type in 1.987.


Your best bet is to use the onchange handler e.g.
<input type="text"
onchange="validateCurrency(this);"
to validate the value entered in the text control, that works reliably
in current browsers. It might even be better to validate all controls in
the onsubmit handler of the form. You have to write the function
validateCurrency of course.
Restricting the user while he types is more difficult, there are key
events fired and you can even cancel them but in many browsers there is
no API to keep track of the caret in the text control while the key
events fire. And pasting into the text control is also not covered by
key events.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
"Rogue Chameleon" <ro*************@gmail.com> wrote in message
news:11**********************@c13g2000cwb.googlegr oups.com...
Hi all

I have a input filed of type "textbox" into which I am expecting to get
currency values (ie. 199.99). Is there a way that I can restrict the
user to only entering 2 values after the decimal point?

I can restrict the maxlength to 5, but that wouldn't stop the user from
type in 1.987.

tia
rogue chameleon


JavaScript can be used though some visitor's browsers may have it disabled.

Try this though there may be a better solution that uses a regular
expression.

<html>
<head>
<title>decimals.htm</title>
<script type="text/javascript">
function decimals(that) {
var s = that.value;
var i = s.indexOf(".");
if (i >= 0 && s.substr(i+1).length > 2) {
alert("Only 2 digits to the right of the decimal are allowed!");
that.value = s.substring(0,s.length-1);
}
}
</script>
</head>
<body>
<form>
<input type="text" size="5" maxlength="5" onkeyup="decimals(this)">
</form>
</body>
</html>
Jul 23 '05 #3
"McKirahan" <Ne**@McKirahan.com> wrote in message
news:7W3nd.113848$R05.15686@attbi_s53...
"Rogue Chameleon" <ro*************@gmail.com> wrote in message
news:11**********************@c13g2000cwb.googlegr oups.com...
Hi all

I have a input filed of type "textbox" into which I am expecting to get
currency values (ie. 199.99). Is there a way that I can restrict the
user to only entering 2 values after the decimal point?

I can restrict the maxlength to 5, but that wouldn't stop the user from
type in 1.987.

tia
rogue chameleon


[snip]

This version is better as it handles the issue of cut-and-pasting a value
"1.234".

<html>
<head>
<title>decimals.htm</title>
<script type="text/javascript">
function decimals(that) {
var s = that.value;
var i = s.indexOf(".");
if (i < 0 || s.substr(i+1).length < 3) return;
alert("Only 2 digits to the right of the decimal are allowed!");
that.value = s.substring(0,i+3);
}
</script>
</head>
<body>
<form>
<input type="text" size="5" maxlength="5" onkeyup="decimals(this)">
</form>
</body>
</html>
Jul 23 '05 #4
Thanks everyone.... I'll try all posted solutions, and see which one
reacts the way I need.

rc

Jul 23 '05 #5
"Rogue Chameleon" <ro*************@gmail.com> wrote in message news:<11**********************@c13g2000cwb.googleg roups.com>...
Hi all

I have a input filed of type "textbox" into which I am expecting to get
currency values (ie. 199.99). Is there a way that I can restrict the
user to only entering 2 values after the decimal point?

I can restrict the maxlength to 5, but that wouldn't stop the user from
type in 1.987.

tia
rogue chameleon


I concur with M. Honnen's caveats in re key handlers - although
onchange can be circumvented by pasting in a copy of the same string.
Similarly, onkeyup alone will fire for mouse/keystroke pasting, but
not for menu pastes. Just for the heck of it...

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>untitled</title>
<script type="text/javascript">
//<![CDATA[

chkfld.running = false; //keep handlers separate
function chkfld(oText)
{
if (chkfld.running) //one at a time
return;
chkfld.running = true;
var msg = '', v = oText.value;
if (!/^\d*\.?\d*$/.test(v))
msg += 'Only numbers, please !';
else if (/\.\d{3,}$/.test(v))
msg += 'Only two decimal places, please !';
if (msg != '')
{
alert(msg);
oText.value = v.replace(/[^\d.]/g,
'').replace(/(\d*)(\.)(\d*)\.(\d*)/g,
'$1$2$3$4').replace(/^(\d*\.\d{2}).+$/,'$1');
return (chkfld.running = false);
}
chkfld.running = false;
}

//]]>
</script>
</head>
<body>
<form>
<input type="text" size="5" maxlength="5" onkeyup="return
chkfld(this)" onblur="return chkfld(this)" />
</form>
</body>
</html>

Tested iewin, NS7.2, Op7 - no mac handy at the moment. I'd shop this
around before using, if at all. Price is right, tho....
Jul 23 '05 #6
You can use a regex to check the format.
The following should allow any number of digits before and including the
decimal point, and only two after it.
/^\d+.\d{2}$/ Checked briefly in IE6.
You can limit the user input to only digits and/or periods but that is
tantamount to terrorizing the user. Unless you have a serious reason, it is
totally unnecessary and should be avoided.

Take Martin Honnens advice and do the validation on form submission.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD><TITLE>validate currency</TITLE>
<script type=text/javascript>
function validateCurrency(sText) {
if(!/^\d+.\d{2}$/.test(sText)) {
alert('not formatted correctly');
document.forms[0].elements[0].focus();
return false;
}
return true;
}
</script>
</HEAD>
<BODY>
<form onsubmit="return validateCurrency(this.elements[0].value)">
<input type=text)></form>
</BODY></HTML>
Finally read Martins post 2 or 3 more times. Though he tends to be brief ALL
of his points are significant.
HTH
Jimbo
"Rogue Chameleon" <ro*************@gmail.com> wrote in message
news:11**********************@c13g2000cwb.googlegr oups.com...
Hi all

I have a input filed of type "textbox" into which I am expecting to get
currency values (ie. 199.99). Is there a way that I can restrict the
user to only entering 2 values after the decimal point?

I can restrict the maxlength to 5, but that wouldn't stop the user from
type in 1.987.

tia
rogue chameleon

Jul 23 '05 #7
"Rogue Chameleon" <ro*************@gmail.com> wrote in message news:<11**********************@f14g2000cwb.googleg roups.com>...
Thanks everyone.... I'll try all posted solutions, and see which one
reacts the way I need.

rc


OK, somewhat better imo. Also minus a linefeed error inflicted by this board. :(

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>untitled</title>
<script type="text/javascript">
//<![CDATA[

$format.running = false; //keep handlers separate
function $format(fld, leaving)
{
if ($format.running) //one at a time
return;
$format.running = true;
var v = fld.value;
if (!/^\d*\.?\d*$/.test(v) || /\.\d{3,}$/.test(v))
{
fld.value = v.replace(/[^\d.]/g,'').
replace(/\.(.*)\./g,'$1.').
replace(/^(\d*\.\d{2}).+$/,'$1');
return ($format.running = false);
}
if (leaving && /\.\d$/.test(fld.value))
fld.value += '0';
$format.running = false;
}

//]]>
</script>
</head>
<body style="font-family:arial;margin:100px;"
onload="document.forms[0].foo.focus()">
<form style="font-size:100%;" onreset="foo.focus()">
$ <input type="text" name="foo" value="" size="8" maxlength="8"
onkeyup="return $format(this,false)"
onblur="return $format(this,true)" />
<input type="reset" value="clear" />
</form>
</body>
</html>
Jul 23 '05 #8
OK...final answer.

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>untitled</title>
<script type="text/javascript">
//<![CDATA[

$format.RE1 = /^\d*\.?\d*$/;
$format.RE2 = /\.\d{3,}$/;
$format.RE3 = /\.(?=[^.]*\.)/g;
$format.RE4 = /[^\d.]/g;
$format.RE5 = /\.(?=[^.]*\.)/g;
$format.RE6 = /^(\d*\.\d{2}).+$/;
$format.RE7 = /(\.\d{0,1})$/;

function $format(fld, leaving)
{
function sReverse(str)
{
for (var s = '', i = str.length - 1; i != -1; --i)
s += str.charAt(i);
return s;
}

var v = fld.value;
if (!$format.RE1.test(v) || $format.RE2.test(v))
{
var ltdot = (fld.dotpos == v.indexOf('.') ?
v.lastIndexOf('.') < fld.dotpos :
v.indexOf('.') < fld.dotpos);
if (ltdot)
v = sReverse(v);
v = v.replace($format.RE3,'');
if (ltdot)
v = sReverse(v);
v =
v.replace($format.RE4,'').replace($format.RE5,''). replace($format.RE6,'$
1');
fld.value = v;
}
fld.dotpos = v.indexOf('.');
if (leaving)
fld.value = v.replace($format.RE7, '$10').replace($format.RE7, '$10');
}

//]]>
</script>
</head>
<body style="font:110% arial;margin:100px;"
onload="f=document.forms[0];f.reset();f.foo.focus()">
<form onreset="foo.focus()">
$ <input type="text" name="foo" value="" size="10" maxlength="8"
style="text-align:center;border:1px black solid;"
onkeyup="return $format(this,false)"
onblur="return $format(this,true)" />
<input type="reset" value="clear" />
</form>
</body>
</html>

The O.P. seems to be long gone, so, maybe someone else can use
this...good exercise, in any event.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #9
LOL, RobB!
Thanks for looking into this so much... your dedication is admirable :)

Jul 23 '05 #10
The Chameleon Lives! :-)
Your welcome, Rogue.

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>untitled</title>
<script type="text/javascript">
//<![CDATA[

cF.RE1 = /^\d*\.?\d*$/;
cF.RE2 = /\.\d{3,}$/;
cF.RE3 = /\.(?=[^.]*\.)/g;
cF.RE4 = /[^\d.]/g;
cF.RE5 = /\.(?=[^.]*\.)/g;
cF.RE6 = /^(\d*\.\d{2}).+$/;
cF.RE7 = /(\.\d{0,1})$/;
cF.RE8 = /^([^.]+)$/;

String.prototype.reverse = function()
{
return this.split('').reverse().join('');
}

function cF(fld, onblur)
{
var v = fld.value;
if (!cF.RE1.test(v) || cF.RE2.test(v))
{
var ltdot = (fld.dotpos == v.indexOf('.') ?
v.lastIndexOf('.') < fld.dotpos :
v.indexOf('.') < fld.dotpos);
if (ltdot)
v = v.reverse();
v = v.replace(cF.RE3,'');
if (ltdot)
v = v.reverse();
v = v.replace(cF.RE4,'').
replace(cF.RE5,'').
replace(cF.RE6,'$1');
fld.value = v;
}
fld.dotpos = v.indexOf('.');
if (onblur)
fld.value = v.replace(cF.RE7, '$10').
replace(cF.RE7, '$10').
replace(cF.RE8, '$1.00');
}

//]]>
</script>
</head>
<body style="font:100% arial;margin:300px;"
onload="f=document.forms[0];f.reset();f.foo.focus()">
<form onreset="foo.focus()">
$ <input type="text" name="foo" value="" size="10" maxlength="8"
style="font:75% arial;text-align:center;border:1px black solid;"
onkeyup="return cF(this,false)"
onblur="return cF(this,true)" />
<input type="reset" value="clear" style="font:75% arial;border:1px black
solid;" />
</form>
</body>
</html>


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Sims | last post by:
Hi, I know how to limit the number of characters using substr, (http://uk.php.net/manual/en/function.substr.php). But when using html that is not going to work because of all the possible tags,...
5
by: Otto Krüse | last post by:
Hi everyone, I'm building a GUI in which I want, amongst other things, for people to fill in there postal code. The postal codes of my country (Holland) are in this format: 1234 AB So for the...
18
by: OrenFlekser | last post by:
Hi I've posted this message couple of days ago, but I can't find it now, so sorry if you see it twice... Anyways - I have a text box, and I want my users to be able to write only in english...
2
by: Gerry Abbott | last post by:
Hi all, Im using an ubound form and recordsets for data update. Id like to trap invalid entries on this form. How can i limit the number of characters the user enters for a particular field. ? ...
4
by: GregG | last post by:
Greetings, I have been working with the new GridView control, and while figuring out most of it's idiosyncrasies on my own, have stumbled upon a problem I cannot seem to resolve. We have...
3
by: DBQueen | last post by:
How can I limit the size of a Memo field? I don't want the user to be able to enter more than 500 characters. Thanks! Andi
3
by: Bob Alston | last post by:
What do others do to limit the number of characters a user can enter in a text box? Do you specify the number of characters exactly so that only that number will fit in the text box, thereby...
2
by: prakashwadhwani | last post by:
I've used Dbase/Clipper for years & Access for a little while now but Access doesn't seem to have any elegant solution to limiting the size of a text box ... i.e. the max number of characters that...
2
by: =?Utf-8?B?TE1X?= | last post by:
I am building a template which has an area for the user to type in whatever information is needed (a form, narrative, whatever). However, I have a limited amount of space on the 1st page of the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.