Link to home
Start Free TrialLog in
Avatar of ellandrd
ellandrdFlag for Ireland

asked on

validate field and fix NaN error

small shopping cart issue - users can enter the amount for the gift voucher.  i validate the input but if the user enters an incorrect format i get NaN returned.  How can I replace this with just 0.00?
function validatePrice() 
{
	function toPoundsAndPennys(n)
	{
		n = n.replace(/[^\d\.+-]/g,'');
        
		if(/\d*\.\d*\./.test(n)) 
			n = n.replace(/(\d*\.\d*)\./,'$1');
         
		n = n.replace(/(\.\d{2})[\d.]*/g,'$1');
        
		return n;
	}
	
	var price = toPoundsAndPennys(document.form.gift-vouchers-price.value);
	
	if(isNaN(price))
	{
		price = 0.00;
	}
	
	document.form.gift-vouchers-price.value = price;
	
	return;
}

Open in new window

Avatar of Phatzer
Phatzer
Flag of United Kingdom of Great Britain and Northern Ireland image

Have you tried this instead? You code seems OK, so there must be something silly wrong!
        if(isNaN(price) == true)
        {
                price = 0.00;
        }

Open in new window

Avatar of pkumarra
pkumarra

Thsi statement will generate an error because of gift-vouchers-price, which is an illegal identifier
var price = toPoundsAndPennys(document.form.gift-vouchers-price.value);

Change this "gift-vouchers-price" to a valid javascript variable name.
Follow the following rules for javascript variable names

The first character must be a letter or an underscore (_). You can't use a number as the first character.

The rest of the variable name can include any letter, any number, or the underscore. You can't use any other characters, including spaces, symbols, and punctuation marks.
Avatar of ellandrd

ASKER

ok i correct my JS variable names and i still have the same issue.

heres my input field:

<input type="text" value="0.00" class="shop-fields" name="gift_vouchers_price" onkeyup="javascript:validatePrice();" onchange="this.value=(1 * this.value).toFixed(2);" onblur="this.value=(1 * this.value).toFixed(2);"

the rest of the code from above is unchanged...
ASKER CERTIFIED SOLUTION
Avatar of shirazti
shirazti
Flag of Sri Lanka image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial