We help IT Professionals succeed at work.

validate if input is a valid currency

-Dman100-
-Dman100- asked
on
I am trying to validate an input that should be a currency.  The input should not contain the currency sign "$" or any commas.  Just straight decimal.  So, if the user was going to enter $1,000.00, it should just be 1000.00 or 1000.  Also, I want to prevent any alpha characters that would be invalid.

Here is what I was trying (see below)

Thanks for any help.

<apex:inputText value="{!Account.Additional_Donation_Amount__c}" id="additionalContribution" onblur="return isNumber();" />

function isNumber() {
    	var regex  = /^\d+(?:\.\d{0,2})$/; 
    	var numStr = document.getElementById('page1:Details:additionalContribution');
		if(regex.test(numStr.value)) {
		    alert("Number is valid");
		}
		else {
			alert("Number is not valid");
		}	
    }

Open in new window

Comment
Watch Question

Owner (Aidellio)
Most Valuable Expert 2015
Commented:
You coul just try parseFloat and test for NaN
-Dman100-Software Consultant

Author

Commented:
I tried parseFloat as you suggested and tested for NaN, but everything is coming back as not a number??  Event if I input 1234
function isNumber() {
    	var numStr = document.getElementById('page1:Details:additionalContribution');
		if(isNaN(parseFloat(numStr))) {
			alert("This is not a valid number");
		}
		else {
			alert("This is a valid number");
		}	
    }

Open in new window

Commented:
You can use this code. While user entering the value itself validate for the valid inputs. Then you can round the value to 2 decimals.

<html>
<head>
<script type="text/javascript">

function isNumber() {
  var numStr = document.getElementById('currency').value;

  if(isNaN(parseFloat(numStr))) {
       alert("This is not a valid number");
  }
  else {
       alert("This is a valid number. Rounded value is :"+parseFloat(numStr).toFixed(2));
  }	
}
</script>
</head>
<body>

<h1>Validate Currency</h1>
<p id="demo">Currency :</p>
<input type="text" onkeyup="this.value = this.value.replace(/[^\d]/g,'')" id="currency" value="">
<button type="button" onclick="isNumber()">Validate</button>

</body>
</html> 

Open in new window