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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

validation currency

Status
Not open for further replies.

YYYYUU

Programmer
Dec 13, 2002
47
GB
I have a string sText.

sText.search(/^\d+\.\d\d$/)

I was using the above to check that a field (value=sText)has the format

#.##

which works very well.

I now need to amend this to allow only 0-9 and format .## (as above) and also to allow commas to be input. I don't need to check that the commas are in the correct place before the decimal point (would be useful but not essential), but putting commas in is optional.

User can put
1.23
23.34
234.23
23,3.34
2,234.34

I've tried many combinations but can't seem to get it right. Can anybody help? Thanks.


 
I'd already written the example so I may as well post it.

Code:
<script>

validateCurrency( "1.23" );
validateCurrency( "I'll give you a fiver for it" );

function validateCurrency( num ) {

	var validate = /^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(\.[0-9]{1,2})?$/.test( num );
	if ( validate )
		alert( num + " is valid." );
	else
		alert( num + " is not valid." );
}

</script>

You definitely should have a look at regexlib.com though.
 
Thanks for your posts which were better than my cheat of replacing the comma with a number for the purpose of testing. I did do an advanced search but obviously searched on words which didn't register.
thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top