Click to See Complete Forum and Search --> : Price Validation


Superfly1611
11-04-2003, 04:08 AM
Hi i'm writing a script to test to see if the user has entered in a valid price.
I've used the below expression to determine if the digits entered are numeric:

if (/\D/.test(this.value))

Now i don't even pretend to understand that expression (Is that a regular expression?) as Javascript to me is a neccesary evil.

If you'd be so kind as to let me know how to include the decimal point in that expression i'd be greatful.

Alternatively i'll happily do the work myself if someone can show me a site that explains (as in a decent explanation) how to write them myself.

Cheers

Charles
11-04-2003, 05:15 AM
If you just want a valid number then use <input type="text" onchange="if (isNaN (this.number)) {alert('That would not appear to be a valid price.'); this.value = ''; this.focus()}">. But if you want to allow for a '$' character you might want to use something more like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>

<style type="text/css">
<!--
label {display:block; margin:1em 0em}
input {display:block}
-->
</style>

<script type="text/javascript">
<!--
String.prototype.reverse = function () {return this.split('').reverse().join('')};

function Price (d) {this.ammount = typeof d == 'number' ? d : Number(d.toString().replace(/[$,]/g, ''))};

Price.prototype.valueOf = function () {return this.ammount};

Price.prototype.toString = function () {
if (isNaN (this.ammount)) return NaN.toString();
var l = Math.floor(Math.abs(this.ammount)).toString();
var r = Math.round((Math.abs(this.ammount) % 1) * 100).toString();
return [(this.ammount < 0 ? '-' : ''), '$', (l.length > 4 ? l.reverse().match(/\d{1,3}/g).join(',').reverse() : l),'.', (r < 10 ? '0' + r : r)].join('');
}
// -->
</script>

<form action="">
<div>
<label>Price<input type="text" onchange="this.value = new Price (this.value); if (isNaN (this.number)) {alert('That would not appear to be a valid price.'); this.value = ''; this.focus()}"></label>
<button type="submit">Submit</button>
</div>
</form>

For details concerning Regular Expressions see http://devedge.netscape.com/library/manuals/2000/javascript/1.3/guide/regexp.html.

Superfly1611
11-04-2003, 07:40 AM
Cheers Charles.
No "$" required so it turned out to be an easy one which is a good thing cause that script meant nothing to me :-/

Will have a look at that site though