(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:
Code:
1000000
1,000,000
1000000.00
$1,000,000.
$1000000
would be "normalized" to (your choice, but perhaps)
Code:
$1,000,000.00
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
1,000,000
$1,000,000
1000000
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):
Code:
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" );
return false;
}
// 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");
return false;
}
// now re-format the value as a simple number for use by server processing:
field.value = value.toFixed(0); // rounds to nearest dollar
return true;
}
Then you might have a validateForm function that does this:
Code:
function validateForm(form)
{
if ( ! checkValue( form.policyAmount ) ) return false;
... perform other validation checks ...
... if any fail, return false ...
... if all succeed ...
return true;
}
****************
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.
Bookmarks