Link to home
Start Free TrialLog in
Avatar of Ratnakar_dr
Ratnakar_dr

asked on

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.
Avatar of ho_alan
ho_alan

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>
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>

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>
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>
So does my script
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>
   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. :-)
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.
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})?$/
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? ;-)
Avatar of Ratnakar_dr

ASKER

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.
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.
ASKER CERTIFIED SOLUTION
Avatar of GwynforWeb
GwynforWeb
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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