Solved

# Float validation

Posted on 2003-11-08
8,537 Views
Hi friends,
i want one answer from u people in Javascript.
I want to chech Float number which should range between given maximum digits of before and after decimal point.
For example if i give 5,2
it should not alow 5 digits before decimal point and 2 digits after decimal point.
it should check on textbox keypress only using javascript.
0
Question by:Ratnakar_dr

LVL 5

Expert Comment

ID: 9706798
0

LVL 31

Expert Comment

ID: 9707176
You must use the onkeyup event to get it to work, try this

<form name='f1'>
<input type="text" name='t1' onkeyup='check(this.value)'>
</form>

<script>
function check(value)
{val=new String
val=value
len=val.length
if (len > 2)
{ch=val.charAt(len-1)
if (ch !='.')
{val= val-ch
if  ( (Math.floor(val) >= 10000) | (Math.floor((val*1000))%10 > 0) ) alert('Error, max of 4 digits before 2 after decimal point')
}
}
}
</script>
0

LVL 31

Expert Comment

ID: 9707312
This is a bit better it corrects the error, (ie removes illegal digit)

<form name='f1'>
<input type="text" name='t1' onkeyup='this.value=check(this.value)'>
</form>

<script>
function check(value)
{
val=value
len=val.length
retval=val
if (len > 2)
{ch=val.charAt(len-1)
if (ch !='.')
{
if  ( (Math.floor(val) >= 10000) | (Math.floor((val*1000)%10) > 0))  {
alert('Error, max of 4 digits before 2 after decimal point')
retval= val.slice(0,len-1)}
}
}
return(retval)
}
</script>

0

LVL 31

Expert Comment

ID: 9707456
oops just noticed you wanted variable digits this doed it

<form name='f1'>
<input type="text" name='t1' onkeyup='this.value=check(this.value,5,3)'>
<input type="text" name='t2' onkeyup='this.value=check(this.value,4,4)'>
<input type="text" name='t3' onkeyup='this.value=check(this.value,6,6)'>
</form>

<script>
function check(value,m,n)
{
val=value
len=val.length
retval=val
if (len > 1)
{ch=val.charAt(len-1)
if (ch !='.')
{
if  ( (Math.floor(val) >= Math.pow(10,m-1)) | (Math.floor((val*Math.pow(10,n))%10) > 0))  {
alert("Error, less than "+ m+" digits before and " +n +" after decimal point required")
retval= val.slice(0,len-1)}
}
}
return(retval)
}
</script>
0

LVL 11

Expert Comment

ID: 9709173
This will warn the user when they've entered more than the allowed number of digits before (maxBefore) or after (maxAfter) the decimal point, and will delete the offending digit.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title></title>

<style type="text/css">
</style>

<script type="text/javascript">

function check(input, maxBefore, maxAfter)
{
eval("var RE = /^\\d{0," + maxBefore + "}(\\.\\d{0," + maxAfter + "})?\$/");

//  regexp used is /^\d{0,maxBefore}(\.\d{0,maxAfter})?\$/

if( !RE.test(input.value) )
{

input.value = input.value.slice(0, -1);
}
}

</script>

<body>

<form>
<input type="text" name="mynumber" onkeyup="check(this, 5, 2);"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
0

LVL 31

Expert Comment

ID: 9709249
So does my script
0

LVL 11

Expert Comment

ID: 9709352
Yeah, but mine's cooler because it's  (a) shorter, (b) passes a reference to the input itself as a parameter to the function, and (c) uses a regular expression that's created on the fly, so there.

<G>
0

LVL 31

Expert Comment

ID: 9710509
Yeah but actually mine is cooler, looking at the scripts mine is the shorter of the 2, there is no need for regular expressions and all other aspects of you code look as if they have been plagerised from mine, including the  passing of a reference to the input itself as a parameter to the function.  And perhaps more importantly mine was posted first without the aid of others work to guide me. :-)
0

LVL 11

Expert Comment

ID: 9710655
Hmmm...

I remembered that you can pass slice() a negative argument, and you didn't.

And I don't know how you can say yours is shorter than mine because my function's three lines shorter, and that's including an extra line for a comment and an extra blank line to buffer it.

I used *one* cunningly crafted regexp instead of several calls to Math.pow() and various and sundry math and logical operators jumbled up  together like sultanas in a bowl of porridge.

And you didn't pass a reference to the input, you passed a reference to the text, which meant you had to use a longer event handler for setting the updated value.

As soon as I read the question, I thought "Mmmmm... regexp time, wonder if anybody's thought of that yet... Nope... nope... nope... cool...!" and got cracking.

Admittedly I didn't even see the question until about 12 hours after you'd posted, so if you're looking for a speed bonus, I'll concede you that, matey.  (To be honest, I expected your answer to be accepted during the interim and was a bit surprised when it wasn't.) And I normally despise eval()s and try to avoid them at all costs, but I couldn't think of any other way to keep from hard coding the bloody thing. I guess if I'd really had my wits about me, I'd've made it global and then recompiled it each time the function was called to save resources as opposed to creating a new instance of RegExp. But then I'd've had a global variable... Fair dinkum, you've convinced me -- I suck. I'm gonna go bang my head in shame against my monitor for awhile.
0

LVL 31

Expert Comment

ID: 9711867
And this is not like sultanas jumbled in a bowl of porridge :-)

eval("var RE = /^\\d{0," + maxBefore + "}(\\.\\d{0," + maxAfter + "})?\$/");
//  regexp used is /^\d{0,maxBefore}(\.\d{0,maxAfter})?\$/
0

LVL 11

Expert Comment

ID: 9712040
I got rid of the eval() and was able to re-use the same RegExp object by using the RegExp constructor and making it a global variable, but it makes the code a wee bit longer:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>/^\d{0,x}\.\d{0,y}\$/ R001Z</title>

<style type="text/css">
form  {font-family:monospace;}
</style>

<script type="text/javascript">

function check()
{
var input = arguments[0];
var reString = "^\\d{0," + arguments[1] + "}(\\.\\d{0," + arguments[2] + "})?\$";

if(!window.RE)
window.RE = new RegExp(reString);
else
RE.compile(reString);

if( !RE.test(input.value) )
{
input.value = input.value.slice(0, -1);
}
}

</script>

<body>

<form>
xxxxx.xx:&nbsp;<input type="text" name="mynumber" onkeyup="check(this, 5, 2);"><br>
xxx.xxx:&nbsp;&nbsp;<input type="text" name="yournumber" onkeyup="check(this, 3, 3);"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

I had to add the call to compile() in case the function gets called again with different parameters.... speaking of which... I did away with the named input parameters for good measure. :-)

Now go finish Googling for the definition of "sultana != muslim queen" whilst I do some work here, eh? ;-)
0

Author Comment

ID: 9712424
Above all scripts are not working properly.
when we copying to the text box it is taking directly.
it is also taking '.' as first charecter.
0

LVL 31

Expert Comment

ID: 9712519
Ratnakar_dr, The question stated on key actions not paste and '.' as a first char is a valid real with fewer than the max before the point.
0

LVL 31

Accepted Solution

GwynforWeb earned 63 total points
ID: 9712556
Checking for a paste is difficult to do properly , that is why form fields are checked prior their submission of on their onblur event ie user moves to next field.
0

LVL 11

Assisted Solution

Zontar earned 62 total points
ID: 9712637
What Gwyn said is ocrrect.

In addition, the onchange event is also useful for this sort of checking. In fact, I started to use onchange, but your question read:

> it should check on textbox keypress only using javascript.

So I used onkeyup, because some browsers don't actually add the character until after the key's been released, so onkeydown is not reliable and onkeypress behaves a bit differently in some browsers as well.

MSIE on Windows does support paste events (onpaste, onbeforepaste) but this is only because it has direct access to the Windows clipboard -- other browsers don't have such access, don't support those events, and those events aren't part of any W3C standard relating to Web pages (or to anything else).

It is possible to detect a { [CTRL] + V } keystroke for a Windows keyboard paste shortcut, but this shortcut isn't used for that purpose on other operating systems.

> it should not alow 5 digits before decimal point and 2 digits after decimal point.

I took this to mean "It should not allow more than 5 digits before the decimal point nor more than 2 digits after the decimal point", and it appears others thought the same thing.

If you want to require at least one digit before the decimal point, you can change the regular expression I offered to

eval("var RE = /^\\d{1," + maxBefore + "}(\\.\\d{0," + maxAfter + "})?\$/");

or

var reString = "^\\d{1," + arguments[1] + "}(\\.\\d{0," + arguments[2] + "})?\$";

If you prefer using onchange instead on onkeyup, additional changes will be required.
0

LVL 16

Expert Comment

ID: 10353182
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Split: GwynforWeb {http:#9712556} & Zontar {http:#9712637}

jAy
EE Cleanup Volunteer
0

## Featured Post

### Suggested Solutions

This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-â€¦
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be \$37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQueryâ€¦