Float validation

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.
Ratnakar_drAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GwynforWebCommented:
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
GwynforWebCommented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

GwynforWebCommented:
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
ZontarCommented:
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>
<head>
<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) )
  {    
    alert("Illegal value.");
   
    input.value = input.value.slice(0, -1);
  }
}

</script>

</head>
<body>

<form>
  <input type="text" name="mynumber" onkeyup="check(this, 5, 2);"><br>
  <input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
0
GwynforWebCommented:
So does my script
0
ZontarCommented:
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
GwynforWebCommented:
   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
ZontarCommented:
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
GwynforWebCommented:
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
ZontarCommented:
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>
<head>
<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) )
  {    
    alert("Illegal value.");    
    input.value = input.value.slice(0, -1);
  }
}

</script>

</head>
<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
Ratnakar_drAuthor Commented:
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
GwynforWebCommented:
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
GwynforWebCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ZontarCommented:
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
jaysolomonCommented:
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}

Please leave any comments here within the next four days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jAy
EE Cleanup Volunteer
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.