Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function to return valid percentage?

Status
Not open for further replies.

MrPeds

Programmer
Jan 7, 2003
219
GB
Hi.

I am a bit of a newbie to JavaScript, so apologies in advance.

I am trying to validate a textbox to see if the value that is typed is of the following format:

23%

or

23

Basically, i am looking to return true or false if the numeric part is less than or equal to 100, and if the % sign is not present on the rhs simply validate that the number is a number.

I was thinking of using a regular expression, but could this be overkill?

Any suggestions are appreciated.

Regards.

MrPeds
 
regular expressions are NEVER overkill [wink]
Code:
<html>
<head>
<script type="text/javascript">

function blah(str) {
   if (/^(\d{1,2}|100)\%?$/.test(str)) {
      alert("passed validation");
   }
   else {
      alert("failed validation");
   }
}

</script>
</head>

<body>

<input type="text" id="txt" />
<input type="button" value="test if number" onclick="blah(document.getElementById('txt').value)" />
</body>
</html>

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
From a high priest of Regular Expressions: kaht. :)#

You could also use the method parseFloat(str, 10) to check the string. parseFloat will allow decimal places in the percentage where parseInt will only return a whole number.

Lee
 
Basically, i am looking to return true or false if the numeric part is less than or equal to 100

If you want to return true or false, you don't even need a test. Presumably, you only want to return true?

Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Indeed, the function should probably only return true.

e.g. if(!fnValid() ){ }

Thanks for your help.

MrPeds
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top