Hi, I created a form and I have a blank field that accepts a currency value.
People can enter this many ways.
So I am writing the value to a database currency field.
It will take the first three, as long as they are "numeric" values.
But if someone types in text it's a mismatch
So I tried using isNaN()
this works for 1000000
But not for 1,000,000
How can I validate this to accept any "numeric" value and not any "text" value?
A couple of ways.
(1) Zap all characters except numbers and decimal point. Then reformat the number into whatever canonical form you prefer. So, for example, all of these inputs:
would be "normalized" to (your choice, but perhaps)That doesn't handle "1 million", though, so you'd have to decide whether you want also handle "1 million" and "1 million 234 thousand" and "seventy four" and whatever.
(2) You could also accept any of the value listed above if you used a regular expression for validation. But, again, handling words is more difficult. Where do you draw the line at what words you allow?
Well I want to only accept a numeric value, or a currency value.
The field is for an insurance policy death benefit, so I think most values entered would be whole numbers and no decimals. 100,000 250,000 500,000
I do not want any text at all to be allowed.
I would like these to be valid
I also guess if someone types in a decimal like $250,000.00 I'll need to address that also.
The thing I am trying to do is catch the input before the form is submitted and if they don't enter it correctly then alert them to change it to the proper format.
Okay...off the top of my head (so whack me upside of it if I made an error):
Now, you could use that function in two ways:
function checkAmount( field )
// zap all non-numeric characters; convert to a number
var value = Number( field.value.replace( /[^\d\.]/g, "" ) );
if ( isNaN(value) )
alert("You must enter a number in the " + field.name + " field" );
// change the number range here as you wish, of course:
if ( value < 10000 || value > 1000000 )
alert("You must specify a number between 10,000 and 1,000,000");
// now re-format the value as a simple number for use by server processing:
field.value = value.toFixed(0); // rounds to nearest dollar
AND/OR you could use it as part of your <form> validation. Say you had
<input name="policyAmount" onchange="checkAmount(this);" />
Then you might have a validateForm function that does this:
<form action="processForm.asp" method="post" onsubmit="return validateForm(this);">
if ( ! checkValue( form.policyAmount ) ) return false;
... perform other validation checks ...
... if any fail, return false ...
... if all succeed ...
The toFixed(0) will, as I said, round the amount to a whole dollar.
You could instead use toFixed(2) to round to the nearest penny.
You could also insert commas every 3 digits, but that's a lot more work and you'd just have to strip them out in your server-side code (I assume ASP?) anyway.